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.
Have you met this question in a real interview?
Yes
Example
Given
[4, 5, 6, 7, 0, 1, 2]
return 0
Note
You may assume no duplicate exists in the array.
二分法, 和search一样。。。其实还要更简单。。。。
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 | 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]; while(beg+1<end){ int mid=beg+(end-beg)/2; if (num[mid]>num[beg]) beg=mid; else end=mid; } return min(num[beg],num[end]); } }; |
No comments:
Post a Comment