Find Minimum in Rotated Sorted Array II
Description
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.
Analysis
这道题目给出来的函数为 int findMin(vector& nums),所以所给序列是以向量的形式给出,而向量里面每一个值的表示是可以用数组的形式来表示的。
对于这道题目,由于给出来的是旋转的有序序列,所以我认为最好的方法就是利用二分法,通过每一个二分比较去掉有序并且不包含最小数的那一部分。
所以我就按照这二分法的形式写了,但是出现了wrong answer的错误。然后我发现这道题目中的序列可能包含重复的数所以我的代码不能判断应该去掉哪一部分。所以我进行了修改,就是当相同时,使low(左边)移动一步再进行比较。
Code
class Solution {
public:
int findMin(vector<int>& nums) {
int len = nums.size();
int low = 0;
int high = nums.size( ) - 1;
int result = nums[0] ;
while(low < high){
int mid = (low + high)/2;
if(nums[mid] > nums[low]){
result = min(nums[low] , result);
low = mid + 1;
}
else if(nums[mid] < nums[low]){
result = min(nums[mid] , result);
high = mid - 1;
}
else{
result = min(result , nums[low]);
low++;
}
}
result = min(nums[low],result);
result = min(nums[high],result);
return result;
}
};