LeetCode:Find Minimum in Rotated Sorted Array

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.

// Source : https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/
// Author : Chao Zeng
// Date   : 2014-12-22
class Solution {
public:
    int findMin(vector<int> &num) {
        int left = 0, right = num.size() - 1;
        int middle = 0;
        while (left < right){
            //已排序数组不一定是升序...
            if (right - left == 1){
                if (num[left] > num[right])
                    middle = right;
                else
                    middle = left;
                break;
            }
            middle = (left + right) >> 1;
            //数组可能并未旋转
            if (num[middle] > num[left] && num[middle] < num[right])
                return num[left];
            if (num[middle] < num[left] && num[middle] > num[right])
                return num[right];

            if (num[middle] >= num[left]){
                left = middle;
            }
            else if (num[middle] <= num[right]){
                right = middle;
            }
        }
        return num[middle];
    }
};


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