Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
Find the minimum element.
You may assume no duplicate exists in the array.
Code:
class Solution {
public:
int findMin(vector<int>& nums) {
int h = nums.size() - 1;
int l = 0;
int minn = INT_MAX;
while(l<=h){
int mid = (l+h)/2;
if(nums[mid] > nums[h]){//if the pivot is contained in nums[mid ...h], we can abandon nums[l...mid]
minn = min(nums[l], minn);
l = mid + 1;
}else{//if the pivot is contained in nums[l ...mid], we can abandon nums[mid...h]
minn = min(nums[mid],minn);
h = mid - 1;
}
}
return minn;
}
};