154. Find Minimum in Rotated Sor
2017-08-03 本文已影响0人
留十夜
ollow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order 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.
The array may contain
仍然是在旋转有序数组中查找最小值,但是此时元素允许重复。有可能遇到如图所示的情况。
此时无法继续判断,只能退回到线性遍历的方式。
//顺序遍历辅助函数
int help(vector<int> &num,int start,int end){
int min_v = num[start];
for(int i=start+1;i<=end;i++){
min_v = min(min_v,num[i]);
}
return min_v;
}
int findMin(vector<int> &num) {
int start=0,end=num.size()-1;
while (start<end) {
if (num[start]<num[end])
return num[start];
int mid = (start+end)/2;
if(num[mid]==num[start] && num[mid]==num[end]){
return help(num,start,end);
}
if (num[mid]>=num[start]) {
start = mid+1;
} else {
end = mid;
}
}
return num[start];
}