Created
February 19, 2013 14:46
-
-
Save pdu/4986521 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| int search(int A[], int n, int target) { | |
| int ans = -1; | |
| int left = 0, right = n - 1; | |
| while (left <= right) { | |
| int mid = (left + right) >> 1; | |
| if (A[mid] == target) { | |
| ans = mid; | |
| break; | |
| } | |
| if (A[mid] >= A[0]) { | |
| if (target > A[mid]) | |
| left = mid + 1; | |
| else if (target < A[0]) | |
| left = mid + 1; | |
| else | |
| right = mid - 1; | |
| } | |
| else { | |
| if (target < A[mid]) | |
| right = mid - 1; | |
| else if (target <= A[n - 1]) | |
| left = mid + 1; | |
| else | |
| right = mid - 1; | |
| } | |
| } | |
| return ans; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment