leetcode153---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.

问题求解:

二分法求解。
1、如果a[mid] > a[left] && a[mid] > a[right],则go right.
2、如果a[mid] < a[left] && a[mid] < a[right],则go left.

class Solution {
public:
    int findMin(vector<int>& nums) {
        int low=0, high=nums.size()-1;
        while(low < high)
        {
            int mid=low + (high-low)/2;
            if(nums[mid] > nums[high])
            {//[4,5,6,7,0,1,2]
                low=mid+1;
            }
            else
            {//[8,9,1,2,3,5,6]
                high=mid;
            }
        }
        return nums[low]>nums[high]?nums[high]:nums[low];
    }
};

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