LeetCode Find Minimum in Rotated Sorted Array II

时间:2021-10-31 08:51:56

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

题目:

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Suppose a sorted array 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.

The array may contain duplicates.

题解:

Find Minimum in Rotated Sorted Array的扩展, 这里有duplicates.

时间复杂度出现了变化,原来可以根据nums[mid] 和 nums[r]的大小关系比较,判断rotate部分是在左还是在右. 依据此来判断下一步是左面查找还是右面查找,现在若是nums[l] == nums[mid]时无法判断。

Time Complexity: O(n). Space: O(1).

AC Java:

 class Solution {
public int findMin(int[] nums) {
if(nums == null || nums.length == 0){
throw new IllegalArgumentException("Input array is null or empty.");
} 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 if(nums[mid]>nums[r]){
l=mid+1;
}else{
r--;
}
} return nums[r];
}
}