Created
November 11, 2013 04:18
-
-
Save charlespunk/7407785 to your computer and use it in GitHub Desktop.
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
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. |
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
public class Solution { | |
public int search(int[] A, int target) { | |
// IMPORTANT: Please reset any member data you declared, as | |
// the same Solution instance will be reused for each test case. | |
return search(A, target, 0, A.length - 1); | |
} | |
public int search(int[] A, int target, int begin, int end){ | |
if(begin > end) return -1; | |
int midle = (begin + end) / 2; | |
if(target == A[midle]) return midle; | |
if(A[midle] >= A[begin]){ | |
if(target < A[midle]){ | |
if(target >= A[begin]) | |
return search(A, target, begin, midle - 1); | |
else return search(A, target, midle + 1, end); | |
} | |
else return search(A, target, midle + 1, end); | |
} | |
else{ | |
if(target < A[midle]) | |
return search(A, target, begin, midle - 1); | |
else{ | |
if(target >= A[begin]) | |
return search(A, target, begin, midle - 1); | |
else return search(A, target, midle + 1, end); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment