LeetCode refers to Offer 11. Rotate the smallest number of the array

topic

Moving several elements from the beginning of an array to the end of the array is called array rotation. Input a rotation of an ascending array, and output the smallest element of the rotated array. For example, the array [3,4,5,1,2] is a rotation of [1,2,3,4,5], and the minimum value of the array is 1. link

Ideas

Two points, just note that the rotation point needs to be judged.
If num[mid]>num[right]it means that the rotation point must be in midthe [mid+1,right]closed interval on the right

Because if the rotation point is on the midleft, midit rightmust be in ascending order and cannot appearnum[mid]>num[right]

Otherwise, the rotation point is in the [left,mid]closed interval.

class Solution {
    
    
    public int minArray(int[] numbers) {
    
    
        int left = 0, right = numbers.length - 1;
        while(left < right){
    
    
            int mid = left + (right - left) / 2;
            if(numbers[mid] > numbers[right])
                left = mid + 1;
            else if(numbers[mid] < numbers[right])
                right = mid;
            else right--;
        }
        return numbers[left];
    }
}

Guess you like

Origin blog.csdn.net/qq_42007742/article/details/107507928