[LeetCode] 153. Looking minimum rotation sorted array

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

Subject description:

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:

Example 1:

输入: [3,4,5,1,2]
输出: 1

Example 2:

输入: [4,5,6,7,0,1,2]
输出: 0

Ideas:

Dichotomy, a dichotomy is to find and middetermine the condition, here we useright

As nums[mid] > nums[right]explained in midincremental region of the left side, indicating the smallest element in the > midregion

As nums[mid] <= nums[rightillustrated in the right half of the mid region is incremented, indicating the smallest element in <= midthe region

Tips:

Generally is the case,

When the while left < rightouter loop output

When while left <= rightcirculating in output


Related questions: 154. Looking minimum rotation sorted array II

Code:

class Solution:
    def findMin(self, nums: List[int]) -> int:
        left = 0
        right = len(nums) - 1 
        while left < right:
            mid = left + (right - left) // 2
            if nums[right] < nums[mid]:
                left = mid + 1
            else:
                right = mid 
        return nums[left]

java

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

Guess you like

Origin www.cnblogs.com/powercai/p/11284305.html