# [LeetCode]154.Find Minimum in Rotated Sorted Array II

#### 【题目】

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.

#### 【代码】

/*********************************
*   日期：2015-01-31
*   作者：SJF0115
*   题目: 154.Find Minimum in Rotated Sorted Array II
*   网址：https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
*   结果：AC
*   来源：LeetCode
*   博客：
**********************************/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
int findMin(vector<int> &num) {
int left = 0,right = num.size() - 1;
int mid = 0;
// num[left] >= num[right] 确保旋转
while(num[left] >= num[right]){
// 分界点
if(right - left == 1){
mid = right;
break;
}//if
mid = left + (right - left) / 2;
// num[left] num[right] num[mid]三者相等
// 无法确定中间元素是属于前面还是后面的递增子数组
// 只能顺序查找
if(num[left] == num[right] && num[left] == num[mid]){
return MinOrder(num,left,right);
}//if
// 中间元素位于前面的递增子数组
// 此时最小元素位于中间元素的后面
if(num[mid] >= num[left]){
left = mid;
}//if
// 中间元素位于后面的递增子数组
// 此时最小元素位于中间元素的前面
else{
right = mid;
}
}//while
return num[mid];
}
private:
// 顺序寻找最小值
int MinOrder(vector<int> &num,int left,int right){
int result = num[left];
for(int i = left + 1;i < right;++i){
if(num[i] < result){
result = num[i];
}//if
}//for
return result;
}
};

int main(){
Solution solution;
//vector<int> num = {0,1,2,3,4,5};
vector<int> num = {1,0,1,1,1,1,1};
int result = solution.findMin(num);
// 输出
cout<<result<<endl;
return 0;
}


#### 【代码二】

class Solution {
public:
int findMin(vector<int> &num) {
int left = 0,right = num.size() - 1;
int mid = 0;
while(left < right){
mid = left + (right - left) / 2;
if(num[mid] > num[right]){
left = mid + 1;
}//if
else if(num[mid] < num[right]){
right = mid;
}//else
// 不能确定最小元素在哪边
else{
--right;
}
}//while
return num[left];
}
};