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.
public class Solution {
public boolean search(int[] A, int target) {
int index = find(A,0,A.length-1,target);
return index==-1? false:true;
}
private int find( int[] arr, int start, int end, int target ){
if( start>end )
return -1;
//如果这部分是递增序列
int index = -1;
if( arr[start]<arr[end] ){
int left = start;
int right = end;
while( left<=right ){
int mid = (left+right)>>1;
if( target>arr[mid] ){
left = mid+1;
}else if( target<arr[mid] ){
right = mid-1;
}else{
index = mid;
break;
}
}
}else{
int mid = (start+end)>>1;
if( arr[mid]==target ){
return mid;
}
index = find( arr, start, mid-1, target );
if( index==-1 ){
index = find( arr, mid+1, end, target );
}
}
return index;
}
}