LeetCode:Find Minimum in Rotated Sorted Array II

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.


// https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
// Author : Chao Zeng
// Date   : 2015-2-1

//有序数组的旋转要注意考虑重复数字,还有利用二分查找的时候,left和right的取值。
class Solution {
public:
    int findMin(vector<int> &num) {
        int left = 0;
        int right = num.size() - 1;
        int minnum = num[0];
        while (left <= right){
            int middle = (left + right) / 2;
            if (num[middle] > num[left] && num[middle] > num[right]){
                left = middle;
            }
            else if (num[middle] < num[right]){
                right = middle;
            }
            else {
                for (int i = 1; i < num.size(); i++){
                    if (minnum > num[i]){
                        minnum = num[i];
                    }
                }
                break;
            }
        }
        return minnum;
    }
};


你可能感兴趣的:(LeetCode,二分查找)