LeetCode:Find Minimum in Rotated Sorted Array

Find Minimum in Rotated Sorted Array

Total Accepted: 74444  Total Submissions: 213031  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
  Array Binary Search




















思路:

1.对子数组sums[lo, hi],如果nums[lo] < nums[hi],则数组没有逆置,直接输出nums[lo];

2.如果nums[lo] >= nums[hi],则数组有逆置,取nums[mid]与nums[lo]比较:

   1)如果nums[lo] <= nums[mid],则最少值在后半部分,这时令 lo = mid + 1,

   2)否则,令 hi = mid;

3.循环1、2直接lo >= hi。


code:


class Solution {
public:
    int findMin(vector<int>& nums) {
        int lo = 0, hi = nums.size() - 1;
        
        while(lo < hi) {
            if(nums[lo] < nums[hi]) return nums[lo];
            
            int mid = (lo + hi) >> 1;
            
            if(nums[lo] <= nums[mid])
                lo = mid + 1;
            else
                hi = mid;
        }
        return nums[lo];
    }
};



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