welcome to my blog
LeetCode 154. Find Minimum in Rotated Sorted Array II (Java版; Hard)
题目描述
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.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
第一次做; 核心: 1)让left和right最终指向同一个元素, 这样才能触发循环终止条件left==right, 如果像之前那样让left指向前部分的末尾,让right指向后部分的开头,就得修改循环终止条件; 2)必须让nums[mid]跟nums[right]比, 否则不能通过绊脚案例{10,1,10,10,10}
/*
绊脚案例{10,1,10,10,10}, 核心: 谁跟谁比? 必须让nums[mid]跟nums[right]比, 否则不能通过绊脚案例
*/
class Solution {
public int findMin(int[] nums) {
int n = nums.length;
if(nums[0]<nums[n-1])
return nums[0];
//
int left=0, right=n-1;
//left==right时,循环终止, 说明left最终指向最小值
while(left<right){
int mid = left + ((right-left)>>1);
//在前部分
if(nums[mid]>nums[right])
left = mid+1;
//在后部分
else if(nums[mid]<nums[right])
right = mid;
//nums[mid]==nums[right], 此时不知道mid在前部分还是后部分, 例如{10,1,10,10,10}
else{
//为了能够返回正确的索引(这里算是个小优化), 可以扩充一下else, 从而保证right--之前,nums[right-1]<=nums[right]
if(nums[right-1]>nums[right]){
left=right;
break;
}
right--;
}
}
return nums[left];
}
}
LeetCode优秀题解; 上面的解法确实能返回最小值, 但是不能保证最小值的索引是正确的, 比如{1,1,1,3,1}, 最后的right是0, 并不是4,
his code is correct to return the minimum value of the array. But in terms of "find the minimum value index" it is not right.
Consider this case: 1 1 1 1 1 1 1 1 2 1 1
the min index returned is 0, while actually it should be 9.
For this case: 2 2 2 2 2 2 2 2 1 2 2
it will return the correct index, which is 8.
The reason is, the pivot index will be passed by at hi--. To avoid this, we can add the following judgement:
为了能够返回正确的索引, 可以扩充一下else, 从而保证right–之前,nums[right-1]<=nums[right]
else {
if (nums[hi - 1] > nums[hi]) {
lo = hi;
break;
}
hi--;
}