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 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.
Subscribe to see which companies asked this question.
找出经过旋转后的有序数组中的最小值。154题和153题是差不多的,只不过是154题允许出现重复的数,而153题不允许。直接解决154题就能解决153题了!用二分法搜索最小值。可以发现旋转之后是分为两个升序部分的。拿mid对应的值与当前子序列的尾部值对比(子序列由left和right索引值确定),如果是大于关系,说明了最小值肯定实在第二部分,而且不在mid处,所以令left=mid+1;如果是小于关系,说明最小值在第一部分,也有可能在mid处,所以令right=mid;如果是相等关系,那就难说了,有可能是类似“0111”和“7111”这两种情况,但left和right总是要改变的不然就无限循环了,可以发现right--总是对的,所以就right--好了。最后返回nums[mid]即可。
代码:
class Solution {
public:
int findMin(vector<int>& nums)
{
int left = 0, right = nums.size()-1, mid;
while(left < right)
{
mid = left + (right - left) / 2;
if(nums[mid] > nums[right])
{
left = mid + 1;
}
else if(nums[mid] < nums[right])
{
right = mid;
}
else
{
right--;
}
}
return nums[left];
}
};