LeetCode 153. Find Minimum in Rotated Sorted Array find the minimum rotation sorted array (C ++)

topic:

Suppose an array sorted in ascending order 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.

Example 1:

Input: [3,4,5,1,2] 
Output: 1

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

analysis:

Given an array of ascending order and was rotating at a certain point. That is, [1,2,3,4,5] may become [3,4,5,1,2]. Wherein the smallest element required, and the array of elements is not repeated.

Iterate over the array directly to obtain the smallest element, when the time complexity of O (n), but obviously, the title given array is "orderly", we can use this feature to quickly solving this problem.

Given a sorted array (non-rotating), we can immediately know the smallest element is the first element in the array, and in this question, we can use to solve the dichotomy, and every division, will certainly produce an ordered array, and a possible orderly array.

For example: [4,5,6,7,0,1,2] if divided into [4,5,6,7] and [0,1,2], both of which are ordered array, we can know immediately two of them is 4 and the minimum value 0, and then seek to once min. Of course, this is the best case, that once divided the two arrays are ordered.

Of course, most cases might be one of the order, and the other is rotating order.

For example: [4,5,6,7,0,1,2] If divided into a [4,5,6] and [7,0,1,2], the array is ordered left side, the right side is rotation order, then immediately left we can get the minimum 4, the right to continue to solve the dichotomy.

Determining whether the ordered array is simple, i.e., the left side of the array elements is less than the right side, it is less than, the array order.

When the two remaining elements of the array when the direct return to the minimum value therein.

program:

class Solution {
public:
    int findMin(vector<int>& nums) {
        if(nums.size()==1) return nums[0];
        int l = 0;
        int r = nums.size()-1;
        return find(nums, l, r);
    }
    int find(vector<int>& nums, int l, int r){
        if(nums[l] < nums[r] || l==r) return nums[l];
        if(r-l == 1) return min(nums[l], nums[r]);
        int mid = (l+r)/2;
        return min(find(nums, l, mid-1), find(nums, mid, r));
    }
};

Guess you like

Origin www.cnblogs.com/silentteller/p/11163491.html