Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e.,0 1 2 4 5 6 7
might 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.
worst case is O(n), like 11111111
tag: binary search
class Solution {
public boolean search(int[] nums, int target) {
int start = 0, end = nums.length - 1;
while (start <= end){
int mid = start + (end - start) / 2;
if (nums[mid] == target) return true;
// left part is sorted
if (nums[start] < nums[mid]){
if (target < nums[start] || target > nums[mid]){
start = mid + 1;
}
else{
end = mid - 1;
}
}
// right part is sorted
else if (nums[start] > nums[mid]){
if (target > nums[end] || target < nums[mid]){
end = mid - 1;
}
else{
start = mid + 1;
}
}
// nums[mid] != target
// nums[start] == nums[mid]
// means found duplicates
else{
start++;
}
}
return false;
}
}