标签:
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.
解题思路:二分查找,首先由中点处查找不重复点
int Find(vector<int> &num, int first, int last) { int mid = (first + last) / 2; int LeftIdx = mid; int RightIdx = mid; while (num[LeftIdx] == num[mid] && LeftIdx >= first) --LeftIdx; while (num[RightIdx] == num[mid] && RightIdx >= first) ++RightIdx; if (LeftIdx<first){ if (RightIdx>last) return num[mid]; else return min(num[mid], Find(num, RightIdx, last)); } else{ if (RightIdx > last) return min(num[mid], Find(num, first, LeftIdx)); else return min(Find(num, first, LeftIdx), min(Find(num, RightIdx, last),num[mid])); } } int findMin(vector<int> &num) { return Find(num, 0, num.size() - 1); }
Find Minimum in Rotated Sorted Array II
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/43702933