题目
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
思路
1 承接上一题 点击打开链接, 二分查找的变形。
2 有了重复的情况之后,问题在于,中间和边缘有可能一样,这样不能区分哪边是排好序的。
3 如此就需要在没法区分的时候,移动一格。
4 最差情况可能O(n),平均时间也肯定下降。
代码
public class Solution {
public boolean search(int[] A, int target) {
if(A.length==0){
return false;
}
int start = 0;
int end = A.length-1;
while(start<=end){
int mid = start + (end - start)/2;
if(A[mid]==target){
return true;
}
if(A[start]<A[mid]){
if(A[start]<=target&&target<A[mid]){
end=mid-1;
}
else start=mid+1;
}
else if (A[start]>A[mid]){
if(A[mid]<target && target<=A[end]){
start = mid+1;
}
else{
end = mid-1;
}
}
else{
start++;
}
}
return false;
}
}