class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
return searchRotatedSortedArray(nums, 0, n-1, target);
}
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 { // 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);
}
}
}
};