题目:
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:
Search in Rotated Sorted Array 的思路,多了要判断 mid left right 相等的情况, 相等则向中间移
Code1:
public boolean search(int[] A, int target) {
if(A.length==0) return false;
int left=0,right=A.length-1;
int mid;
boolean flag=false;
while(left<=right){
mid=(left+right)/2;
flag=false;
if(A[mid]==target){
return true;
}
if(mid!=left && A[left]==A[right]) {
left++;
flag=true;
}
if(mid!=right && A[right]==A[mid]){
right--;
flag=true;
}
if(flag) continue;
if(A[left]<=A[mid]){
if(A[left]<=target && target<A[mid]){
right=mid-1;
}else{
left=mid+1;
}
}else{
if(A[mid]<target && target<=A[right]){
left=mid+1;
}else{
right=mid-1;
}
}
}
return false;
}
Code2:
public boolean search(int[] A, int target) {
if(A.length==0) return false;
int left=0,right=A.length-1;
int mid;
while(left<=right){
mid=(left+right)/2;
if(A[mid]==target) return true;
if(A[left]<target && target<A[mid]) right=mid-1; //无等号
else if(A[mid]<target && target<A[right]) left=mid+1; //无等号
else{
if(target!=A[left]) left++; //缩小范围并同时检测边界值
else return true;
if(target!=A[right]) right--;
else return true;
}
}
return false;
}
备注:
搜索时最好建立坐标系,考虑所有情况