leetcode154. sorted array to find the minimum rotational II

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.

Note that there may be repeated elements in the array.

Example 1:

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

Example 2:

Input: [2,2,2,0,1]
Output: 0

Description:

    This question is to find rotation extending minimum sorted array topic.
    Allow duplicate will affect the time complexity of the algorithm do? It will affect how, and why?

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

answer:

Still the same, 33,81 questions before watching, do not say.

 1 class Solution {
 2     public int findMin(int[] nums) {
 3         int l=0;
 4         int r=nums.length-1;
 5         while(l<=r)
 6         {
 7             if(nums[l]<nums[r])
 8                 return nums[l];
 9             int mid=l+(r-l)/2;
10             if(nums[mid]>nums[l])
11                 l=mid+1;
12             else if(nums[mid]<nums[r])
13                 r=mid;
14             else
15                 l++;
16         }
17         return nums[r];
18     }
19 }
View Code

 

Guess you like

Origin www.cnblogs.com/cold-windy/p/11875619.html