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.

思路:用binary search, 一半是有序的,一半是无序的。minimum在无序的子数组中。


class Solution {
public:
    int findMin(vector<int> &num) {
        int start = 0;
        int end = num.size() - 1;
        int middle;
        while(start < end) {
            //not reverse, return.
            if(num[start] < num[end])
                return num[start];
            middle = (start + end )/ 2;
            if(num[middle] >= num[start])
            {
                start = middle + 1;
            }else{
                end = middle;
                start += 1;
            }
        }
        return num[end];
    }
};


你可能感兴趣的:(LeetCode,array,sorted,rotated)