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.
The array may contain duplicates.
如果有dup,会出现mid=beg的情况,二分不出来,只能移动beg了。。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Solution { public: /** * @param num: a rotated sorted array * @return: the minimum number in the array */ int findMin(vector<int> &num) { if (num.empty()){ return -1; } int beg=0; int end=num.size()-1; if (num[beg]<num[end]) return num[beg]; int mid=0; while(beg+1<end){ mid=beg+(end-beg)/2; if(num[mid]>num[beg]){ beg=mid; } else if (num[mid]<num[beg]){ end=mid; } else{ beg++; } } return min(num[beg], num[end]); } }; |
No comments:
Post a Comment