Suppose a sorted array is rotated on 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.
Assume no duplicate exists in the array.
Analysis:
For arrays that do not contain duplicate elements a[0, ..., n-1], if A[MID] < A[high], indicate the minimum value between A[low, mid].
Otherwise, between A[mid + 1, high].
1 intFindmin (vector<int> &num)2 {3 intLow =0, high = Num.size ()-1, Mid =0;4 5 while(Low <High )6 {7Mid = (low + high)/2;8 if(Num[mid] <Num[high])9High =mid;Ten Else OneLow = mid +1; A } - - returnNum[low]; the}
If A contains duplicate elements, you need to add the judgment a[mid] = = A[high], at this time cannot use two points, such as [1, 1, 0, 1] and [0, 1, 1, 1], the smallest element
Can be at A[mid, high], or A[low, mid], at which point the range can be reduced by high--,.
1 intFindmin (vector<int> &num)2 {3 intLow =0, high = Num.size ()-1, Mid =0;4 while(Low <High )5 {6Mid = (low + high)/2;7 if(Num[mid] = =Num[high])8high--;9 Else if(Num[mid] <Num[high])TenHigh =mid; One Else ALow = mid +1; - } - the returnNum[low]; -}
Leetcode 154/153. Find Minimum in rotated Sorted Array && II