Created
November 15, 2021 03:21
-
-
Save tolinwei/70b54547911ac1345222a1cbeb400edc to your computer and use it in GitHub Desktop.
Search in rotated 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
class Solution { | |
public int search(int[] nums, int target) { | |
if (nums == null || nums.length == 0) { | |
return -1; | |
} | |
// find pivot | |
int left = 0; | |
int right = nums.length - 1; | |
while (left < right) { | |
int mid = left + (right - left) / 2; | |
// first if may not always work, for example [3, 1] & 1 | |
if (nums[mid] == target) { | |
return mid; | |
} else if (nums[mid] > nums[right]) { | |
left = mid + 1; | |
} else if (nums[mid] < nums[right]) { | |
right = mid; | |
} | |
} | |
// now left is pivot | |
int pivot = nums[left]; | |
System.out.println("target: " + target); | |
System.out.println("pivot: " + pivot); | |
// System.out.println("nums[right]: " + nums[right]); | |
// must use target >= pivot, for [3,1] & 1 | |
if (target >= pivot || target <= nums[nums.length - 1]) { | |
System.out.println("here"); | |
// left remains | |
right = nums.length - 1; | |
} else { | |
System.out.println("there"); | |
right = left; | |
left = 0; | |
} | |
while (left < right) { | |
int mid = left + (right - left) / 2; | |
if (nums[mid] == target) { | |
return mid; | |
} else if (nums[mid] < target) { | |
left = mid + 1; | |
} else if (nums[mid] > target) { | |
right = mid - 1; | |
} | |
} | |
return nums[left] == target ? left : -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment