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.
Example
Given [1, 1, 0, 1, 1, 1]
and target = 0
, return true
.
Given [1, 1, 1, 1, 1, 1]
and target = 0
, return false
.
public class Solution {
/**
* param A : an integer ratated sorted array and duplicates are allowed
* param target : an integer to be search
* return : a boolean
*/
public boolean search(int[] A, int target) {
if(A.length == 0) return false;
int left = 0, right = A.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(A[mid] == target) return true;
if(A[mid] < target) {
if(A[mid] >= A[left]) { //与I的区别
left = mid + 1;
} else {
if(target <= A[right]) left = mid + 1;
else right = mid - 1;
}
} else {
if(A[mid] <= A[right]) { //与I的区别
right = mid - 1;
} else {
if(target >= A[left]) right = mid - 1;
else left = mid + 1;
}
}
}
return false;
}
}