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 mid
determine the condition, here we useright
As nums[mid] > nums[right]
explained in mid
incremental region of the left side, indicating the smallest element in the > mid
region
As nums[mid] <= nums[right
illustrated in the right half of the mid region is incremented, indicating the smallest element in <= mid
the region
Tips:
Generally is the case,
When the while left < right
outer loop output
When while left <= right
circulating 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];
}
}