Problem:
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.
Solutions:This is a typical problem that can be used using binary search algorithm. Note that the rotated sorted array must be longer than 3. The exceptional cases, i.e. the subarray of size 2 or smaller, should be dealt with seperately. Another point of this problem is the input array does not include duplicates. The case when the array contains duplicates will be dealt with in the problem 154.
int findMin(vector<int> &num) {
if(num.size() == 1)
return num[0];
int iStart = 0, iEnd = num.size() - 1;
for(int iMiddle = (iEnd + iStart + 1)/2; iStart != iEnd; iMiddle = (iEnd + iStart + 1)/2) {
if(num[iStart] < num[iEnd])
return num[iStart];
if(iStart == iEnd - 1)
return (num[iStart] < num[iEnd] ? num[iStart] : num[iEnd] );
if(num[iStart] < num[iMiddle]) {
if(num[iMiddle] > num[iMiddle + 1])
return num[iMiddle + 1];
else
iStart = iMiddle + 1;
} else {
if(num[iMiddle] < num[iMiddle - 1])
return num[iMiddle];
else
iEnd = iMiddle - 1;
}
}
}