LeetCode Find Minimum in Rotated Sorted Array

时间:2023-03-09 18:48:59
LeetCode Find Minimum in Rotated Sorted Array

原题链接在这里:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/

题目:

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.

题解:

Binary Search, 与Find Peak Element类似.

如果nums[mid] < nums[r]说明右边一段是sorted的, minumum 只能出现在包括中点的左边一段.

反之, 说明左边一段是sorted的, minimum只能出现在不包括中点的右边一段.

最后返回nums[r].

Time Compelxity: O(logn). n = nums.length.

Space: O(1).

AC Java:

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

类似Search in Rotated Sorted ArrayFind Minimum in Rotated Sorted Array IISingle Element in a Sorted Array.