<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 30px;">Follow up for "Search in Rotated Sorted Array":<br style="box-sizing: border-box;" />What if <span style="box-sizing: border-box;">duplicates</span> are allowed?</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 30px;">Would this affect the run-time complexity? How and why?</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 30px;">Write a function to determine if a given target is in the array.</p>
----------------------------------------------------------------------
public class Solution {
public boolean search(int[] A, int target) {
if(A.length < 1)
return false;
if(A.length < 2)
return A[0] == target;
int low=0, high=A.length-1, mid=(low+high)/2;
while(low <= high){
mid=(low+high)/2;
if(A[mid] == target)
return true;
if(A[mid] > A[low]){
if(A[low]<=target && target<A[mid])
high=mid;
else
low=mid+1;
}else if(A[mid] < A[low]){
if(A[mid]<target && target<=A[high])
low=mid+1;
else
high=mid;
}else
low ++;
}
return false;
}
}
思路:不多说了看
Search in Rotated Sorted Array。
tricky的内容就是如果遇到一样的low++知道遇到不同的数字