81. Search in Rotated Sorted Array II
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e.,0 1 2 4 5 6 7might become4 5 6 7 0 1 2).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
思路:应对mid=end,end--
public boolean search(int[] nums, int target) {
int lo = 0;
int hi = nums.length-1;
while(lo<=hi){
int mid = (lo+hi)/2;
if (nums[mid]==target){
return true;
}
if (nums[mid]<nums[hi]){ //right half sorted
if (target>nums[mid]&&target<=nums[hi]){
lo = mid+1;
}else{
hi = mid-1;
}
}else if (nums[mid]>nums[hi]){ //left half sorted
if (target<nums[mid]&&target>=nums[lo]){
hi = mid-1;
}else{
lo = mid+1;
}
}else{
hi--;
}
}
return false;
}
}