问题:
Follow up for "Search 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
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
解决:
① 本题允许有重复的值,这样Search in Rotated Sorted Array中的条件就不能判断哪一边为有序序列了。所以要将mid移动一下。比如:{1,3,1,1,1,1}
如果nums[start] <= nums[mid] 条件就不能确定[start mid]区间为递增有序序列,我们就把该条件分成两个字条件:
nums[start] < nums[mid] 则 [start mid]区间为递增有序序列
nums[start] = nums[mid] 则[start mid]区间不能确定,那就start ++,往下一步看看即可。
class Solution {//1ms
public boolean search(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while(start <= end){
int mid = (end - start) / 2 + start;
if(nums[mid] == target){
return true;
}
if(nums[start] < nums[mid]){
if(nums[start] <= target && target < nums[mid]){
end = mid - 1;
}else{
start = mid + 1;
}
}else if(nums[start] > nums[mid]){
if(nums[mid] < target && target <= nums[end]){
start = mid + 1;
}else{
end = mid - 1;
}
}else{
start ++;
}
}
return false;
}
}