Created
February 28, 2020 08:40
-
-
Save alldroll/c89937e20a89f466ec786febd513f237 to your computer and use it in GitHub Desktop.
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/find-minimum-in-rotated-sorted-array | |
| func findMin(nums []int) int { | |
| n := len(nums) | |
| i, j := 0, n | |
| minItem := (1 << 31) - 1 | |
| for i < j { | |
| h := (i + j) >> 1 | |
| if nums[i] < nums[h] { | |
| // [i, h] is sorted, we can check the first item for min | |
| minItem = min(nums[i], minItem) | |
| if nums[h] > nums[n - 1] { | |
| // we found pivot | |
| i = h + 1 | |
| } else { | |
| j = h | |
| } | |
| } else { | |
| if nums[h] <= nums[n - 1] { | |
| // [h, n - 1] is sorted, we can check the median item for min | |
| minItem = min(nums[h], minItem) | |
| j = h | |
| } else { | |
| i = h + 1 | |
| } | |
| } | |
| } | |
| return minItem | |
| } | |
| func min(a, b int) int { | |
| if a < b { | |
| return a | |
| } | |
| return b | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment