Last active
December 16, 2015 19:39
-
-
Save daifu/5486986 to your computer and use it in GitHub Desktop.
Search in Rotated Sorted Array II
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. | |
Algorithm: | |
1. Based on the algorithm from Search in Rotated Sorted Array I, by adding | |
if A[mid] == A[right], and then decrease right--; | |
else if they are different, then follow the origional algorithm to move | |
the pointer. | |
*/ | |
public class Solution { | |
public boolean search(int[] A, int target) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
int left = 0; | |
int right = A.length - 1; | |
while(right >= left) { | |
int mid = (right + left) / 2; | |
if(A[mid] > A[right]) { | |
if(A[left] <= target && target < A[mid]) { | |
right = mid - 1; | |
} else if(A[mid] == target) { | |
return true; | |
} else { | |
left = mid + 1; | |
} | |
} else if(A[mid] < A[right]) { | |
if(A[mid] < target && target <= A[right]) { | |
left = mid + 1; | |
} else if(target == A[mid]) { | |
return true; | |
} else { | |
right = mid - 1; | |
} | |
} else if(A[mid] == target) { | |
return true; | |
} else { | |
right--; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment