Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 21, 2013 13:53
Show Gist options
  • Select an option

  • Save pdu/4586212 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4586212 to your computer and use it in GitHub Desktop.
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. http://leetcode.com/onlinejudge#question_33
int get_biggest(int A[], int n) {
int ret = 0;
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = (left + right) >> 1;
if (A[mid] >= A[0]) {
ret = max(ret, mid);
left = mid + 1;
}
else
right = mid - 1;
}
return ret;
}
int bsearch(int A[], int left, int right, int target) {
while (left <= right) {
int mid = (left + right) >> 1;
if (A[mid] > target)
right = mid - 1;
else if (A[mid] < target)
left = mid + 1;
else
return mid;
}
return -1;
}
class Solution {
public:
int search(int A[], int n, int target) {
if (n == 0)
return -1;
if (A[0] < A[n - 1])
return bsearch(A, 0, n - 1, target);
else {
int bigid = get_biggest(A, n);
if (target >= A[0])
return bsearch(A, 0, bigid, target);
else
return bsearch(A, bigid + 1, n - 1, target);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment