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.
旋转一次的有序数组含有重复的元素遍历数组找到旋转的位置,左边、右边都是递增的
如果target在左边,在左侧二分搜索
否则在右侧二分搜索
public class Solution {
public boolean search(int[] A, int target) {
int middle = 0;
int start = 0;
int end = A.length;
if(end==0)
return false;
int i;
for(i=1;i<end;i++){ //找到断点
if(A[i]<A[i-1])
break;
}
if(target>=A[0]&&target<=A[i-1]){
start=0;
end=i;
}
else
{
start=i;
end=A.length;
}
while (true) {
middle = (start + end) / 2;
if (start >= end)
return false;
if (A[middle] == target)
return true;
if(A[middle] < target)
start=middle+1;
else
end=middle;
}
}
}