Find the minimum rotation LeetCode 153 sorted array

Link: https: //leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array

Suppose ascending order according to the array was rotated in a previously unknown point.

(E.g., array [0,1,2,4,5,6,7] may become [4,5,6,7,0,1,2]).

Find the smallest elements.

You can assume that there is no duplication of elements 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

 

 

This question first of all in order to understand that the idea is very simple, when the array is rotated from the starting position to the rotation number of the last paragraph, must be smaller than the number of the far left, of course, must be younger than most from the left to the point of rotation number . For example [1,2] is less than [3,4,5]. This property can be used as Sec. So first of all we are looking for a smaller number than the number in the leftmost. But doing so will be a problem, when there is no rotation of the array, this property does not exist. So to add a misjudge the front, without rotation, when the first number is directly returned to the original array.

c ++ code is as follows:

 1 class Solution {
 2 public:
 3     int findMin(vector<int>& nums) {
 4         if(nums.empty()) return nums.size();
 5         if(nums[nums.size() - 1] >= nums[0]) return nums[0];
 6         int n = nums[0];
 7         int l = 0, r = nums.size() - 1;
 8         while(l < r){
 9             int mid = l + r >> 1;
10             if(nums[mid] <= n) r = mid;
11             else l = mid + 1;
12         }
13         return nums[r];
14     }
15 };

A more simple method, the step can be omitted wrongly, we can use less than all of the rotation / non-rotation of the array as the nature of the last number, it returns the first point of this nature.

c ++ code is as follows:

 1 class Solution {
 2 public:
 3     int findMin(vector<int>& nums) {
 4         if(nums.empty()) return nums.size();
 5         int l = 0, r = nums.size() - 1;
 6         while(l < r){
 7             int mid = l + r >> 1;
 8             if(nums[mid] <= nums.back()) r = mid;
 9             else l = mid + 1;
10         }
11         return nums[r];
12     }
13 };

There is also a small tips, in c ++, the last element of the array can be used nums.back () to indicate whether the array is empty can nums.empty () to represent.

Guess you like

Origin www.cnblogs.com/hellosnow/p/11578259.html