Problem
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.
Code
int rs_r(int A[], int l,int r, int target){ if(l == r) { if(A[l - 1] == target) return l - 1; return -1; } int mid = (l + r)/2; if(A[mid - 1] >= A[l - 1]){ if(target == A[mid - 1]){ return mid - 1; } else if(target < A[mid - 1] && target >= A[l - 1]) rs_r(A,l,mid - 1,target); else rs_r(A,mid + 1,r,target); } else{ if(target == A[mid - 1]){ return mid - 1; } else if(target > A[mid - 1] && target <= A[r - 1]) rs_r(A,mid + 1,r,target); else rs_r(A,l,mid - 1,target); } } int search(int A[], int n, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. int l = 1,r = n; return rs_r(A,l,r,target); }
No comments:
Post a Comment