Last active
November 10, 2018 17:41
-
-
Save hsaputra/d2cc3a1fbe8cbb106b0d98679272d8c3 to your computer and use it in GitHub Desktop.
33. Search in Rotated Sorted Array
This file contains 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 { | |
// [4,5,6,7,0,1,2,3] | |
// [6,7,0,1,2,3,4,5] | |
public int search(int[] nums, int target) { | |
if (nums == null || nums.length == 0) { | |
return -1; | |
} | |
final int numsLen = nums.length; | |
int lo = 0; | |
int hi = numsLen - 1; | |
while (lo < hi) { | |
int mid = (lo + hi)/2; | |
if (nums[mid] == target) { | |
return mid; | |
} | |
// check if first half is sorted | |
if (nums[lo] <= nums[mid]) { | |
if (target >= nums[lo] && target < nums[mid]) { | |
hi = mid - 1; | |
} else { | |
lo = mid + 1; | |
} | |
} else { | |
// if not the other one must be | |
if (target <= nums[hi] && target > nums[mid]) { | |
lo = mid + 1; | |
} else { | |
hi = mid - 1; | |
} | |
} | |
} | |
return nums[lo] == target ? lo : -1; | |
} | |
} |
Author
hsaputra
commented
Nov 10, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment