多写限制条件可以加快调试速度。
=======
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.
这道题,会看到重复的数字,去重(判断相等的话,就移位,这是给我自己写的)的办法可以很好解决。
因为循环移位的数组,mid在中间划分,会变为两个不对称的子数组:
其中一个有序,另一个无序。只要抓住这一条,就可以很好利用二分搜索去掉不想要的那一部分了。
这一体后面会对临界值处理,可以另外加判断条件。
if(nums.size()==)return ;
int left = ;
int right = nums.size()-;
int mark = right;
while(left<=right){
if(left+==right){
mark = nums[left]<nums[mark]?left:mark;
mark = nums[right]<nums[mark]?right:mark;
break;
}
int mid = (left+right)/;
if(nums[mid]<nums[right]){
if(nums[mid]<nums[mark])
mark = mid;
right = mid-;
}else if(nums[mid]>nums[right]){
if(nums[left]<nums[mark])
mark = mid;
left = mid+;
}else{
right--;
}
}///while if(left<nums.size())
mark = nums[left]<nums[mark]?left:mark;
if(right>)
mark = nums[right]<nums[mark]?right:mark;
return nums[mark];