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.

二分查找就行了。

 class Solution {
public:
int findMin(vector<int> &arr) {
if (arr.empty()) return -;
int l = , h = arr.size() - , m, min = INT_MAX;
while (l <= h) {
m = l + (h - l) / ;
if (arr[m] >= arr[l]) {
if (min > arr[l]) min = arr[l];
l = m + ;
} else {
if (arr[m] < min) min = arr[m];
h = m - ;
}
}
return min;
}
};

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?
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.

 class Solution {
public:
int findMin(vector<int> &arr) {
if (arr.empty()) return -;
int l = , h = arr.size() - , m, min = INT_MAX;
while (l <= h) {
m = l + (h - l) / ;
if (arr[m] > arr[l]) {
if (min > arr[l]) min = arr[l];
l = m + ;
} else if (arr[m] < arr[l]) {
if (arr[m] < min) min = arr[m];
h = m - ;
} else {
if (arr[m] < min) min = arr[m];
l++;
}
}
return min;
}
};
05-11 02:38