Last active
January 1, 2026 15:22
-
-
Save rtsoy/1510b1bbd86cb1ea9f8f9b027f5239f3 to your computer and use it in GitHub Desktop.
33. Search in Rotated Sorted Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://leetcode.com/problems/search-in-rotated-sorted-array/ | |
| // | |
| // Time: O(log n) | |
| // Space: O(1) | |
| // | |
| // n = number of elements in the array | |
| // .................... // | |
| func search(nums []int, target int) int { | |
| n := len(nums) | |
| last := nums[n-1] | |
| lo, hi := 0, n-1 | |
| for lo <= hi { | |
| mi := lo + (hi-lo)/2 | |
| if nums[mi] > last { | |
| lo = mi + 1 | |
| } else { | |
| hi = mi - 1 | |
| } | |
| } | |
| min := lo | |
| if target > last { | |
| lo, hi = 0, min | |
| } else { | |
| lo, hi = min, n-1 | |
| } | |
| for lo <= hi { | |
| mi := lo + (hi-lo)/2 | |
| if nums[mi] == target { | |
| return mi | |
| } | |
| if nums[mi] > target { | |
| hi = mi - 1 | |
| } else { | |
| lo = mi + 1 | |
| } | |
| } | |
| return -1 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment