3 years ago
Binary search
nums[mid], we are either in the left sorted portion or the right sorted portion. In example, 1, left sorted portion would be 3, 4, 5. When this happens, we would want to move to the right sorted portion, because the right sorted portion has the lower numbered elements.nums[mid] is in the left sorted portion, i.e. nums[mid] >= nums[l], we would need to move to the right sorted portion, so we would update ans and set left pointer to mid + 1. The reason for greater than or equal is for an edge case where nums[mid] == nums[l] (i.e. only one element in current bounds)nums[l] < nums[r], we possibly update our answer and immediately returnTake note of two conditions:
nums[l] < nums[r]
return min(ans, nums[l]) will return 1 as the correct answerreturn min(ans, nums[l]) will return 1 as the correct answer.nums[m] >= nums[l]
mid == l| Time | Space | Explanation |
|---|---|---|
O(log n) | O(1) |