Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Example For [4, 5, 1, 2, 3] and target=1, return 2.
For [4, 5, 1, 2, 3] and target=0, return -1.
Solution: Rotated array has a half array that is sorted. So we can use binary search.
public int search(int[] A, int target) {
if(A == null || A.length == 0) {
return -1;
}
int start = 0, end = A.length - 1;
while(start <= end) {
int mid = start + (end - start) / 2;
if(A[mid] == target) {
return mid;
}
else if(A[start] < A[mid]) {
if(A[start] <= target && A[mid] >= target) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
else {
if(A[mid] <= target && target <= A[end]) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
}
return -1;
}
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?
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.
Solution: Skip duplicate elements. If all elements are duplicate except target, we need search one by one and time complexity become O(N).
public boolean search(int[] A, int target) {
if(A == null || A.length == 0) {
return false;
}
int start = 0, end = A.length - 1;
while(start <= end) {
int mid = start + (end - start) / 2;
if(A[mid] == target) {
return true;
}
else if(A[start] < A[mid]) {
if(A[start] <= target && A[mid] >= target) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
else if(A[start] > A[mid]) {
if(A[mid] <= target && target <= A[end]) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
else {
start++;
}
}
return false;
}