class Solution {
public:
bool search(vector<int>& nums, int target) {
int index = searchRotatedSortedArray(nums, 0, nums.size() - 1, target);
return (index == -1) ? false : true;
}
private:
int searchRotatedSortedArray(vector<int>& A, int start, int end, int target) {
if(start > end) {
return -1;
}
int mid = start + (end-start)/2;
if(A[mid] == target) {
return mid;
}
if(A[mid] < A[end]) {
// right half sorted
if(target > A[mid] && target <= A[end]) {
return searchRotatedSortedArray(A, mid+1, end, target);
} else {
return searchRotatedSortedArray(A, start, mid-1, target);
}
}
else if (A[mid] > A[end]){ // left half sorted
if(target>=A[start] && target<A[mid]) {
return searchRotatedSortedArray(A, start, mid-1, target);
} else {
return searchRotatedSortedArray(A, mid+1, end, target);
}
} else {
return searchRotatedSortedArray(A, start, end-1, target);
}
}
};