leetcode 153. Find the minimum value in a rotated sorted array (good solution)

Code:

class Solution {
    public int findMin(int[] nums) {
        int left=0,right=nums.length-1;
        int refer=nums[right];

        while (left<right){
            int mid=left+(right-left)/2;

            if(nums[mid]>refer){
                left=mid+1;
            }else {
                right=mid;
            }
        }

        return nums[left];
    }
}

answer:

        From the meaning of the question, we know that the parameters passed in are rotated increasing arrays, such as 3, 4, 5, 1, 2, which are obtained by rotating 1, 2, 3, 4, 5, and the characteristics of this rotated array We can clearly see it through a picture, taking 3, 4, 5, 1, 2 as an example


        We can see that most of the incremental arrays after rotation have such a structure. We divide the data into two intervals, and the answer to be obtained is located at the left boundary of the interval below.

        ​ ​ ​ We can use the last data of the array as a reference reference to select a number nums[i] in the array. This number may be located in the upper and lower intervals.

        ​ ​ ​ (1). When nums[ i ] > refer, it means that the number is in the upper range, then we can boldly remove the data pointed to by the i subscript and the data on the left

        (2). When nums[i] <= refer, it means that the number is located in the following interval, then we can boldly remove the data to the right of the i subscript (but we cannot be sure whether the i subscript points to exactly us required data, so we cannot remove the data pointed to by the i subscript)

        Through the above analysis, we have been able to determine that the question has a two-stage nature, so we can solve the problem through the dichotomy method

        Take nums = 3, 4, 5, 1, 2 as an example, use the L and R pointers to point to both ends of the array, mid = left+(right-left)/2= 2. At this time, the R pointer points to the end of the array. We can record a piece of data as a reference value, refer = nums[ R ] = 2

        At this time nums[mid] = 5 > refer, so in the above interval, we can boldly remove the mid pointer and the data to the left of the mid pointer, let L = mid+1

3        4        5        1        2

L                 mid               R

        Calculate the middle value mid = 3, at this time nums[ mid ] = 1 < refer, so in the following interval, we can boldly remove the data to the right of mid and let R = mid 

3        4        5        1        2

                               L       R

                              mid 

        When the L and R pointers meet, we find the left boundary of the following interval and directly return nums[L]

3        4        5        1        2

                               L       

                               R

Guess you like

Origin blog.csdn.net/q322359/article/details/135002659