154. Find Minimum in Rotated Sorted Array II

problem

元素可能重複

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int findMin(vector<int>& nums) {
int n = nums.size();
int l = 0, r = n-1;
while(l<r){
int mid = l + (r-l)/2;
// 代表最小值會在 [mid+1, r] 之間
if(nums[mid] > nums[r]) l = mid+1;
// 下次搜尋區間
else if(nums[mid] < nums[r] ) r = mid;
else r--;
}
return nums[l];
}
};

analysis

  • time complexity O(logn)
  • space complexity O(1)