LeetCode 154. Find Minimum in Rotated Sorted Array II
原题链接在这里: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:
1 class Solution { 2 public int findMin(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 throw new IllegalArgumentException("Input array is null or empty."); 5 } 6 7 int l = 0; 8 int r = nums.length-1; 9 while(l<r){ 10 int mid = l+(r-l)/2; 11 if(nums[mid]<nums[r]){ 12 r=mid; 13 }else if(nums[mid]>nums[r]){ 14 l=mid+1; 15 }else{ 16 r--; 17 } 18 } 19 20 return nums[r]; 21 } 22 }