Created
February 23, 2020 22:10
-
-
Save wushbin/6b6ba6959713e127158ff7304184ee94 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
| class Solution { | |
| public int[] searchRange(int[] nums, int target) { | |
| if (nums == null || nums.length == 0) { | |
| return new int[]{-1, -1}; | |
| } | |
| int l = findFirst(nums, target); | |
| int r = findLast(nums, target); | |
| return new int[]{l, r}; | |
| } | |
| private int findFirst(int[] nums, int target) { | |
| int l = 0; | |
| int r = nums.length - 1; | |
| while(l < r) { | |
| int mid = l + (r - l) / 2; | |
| if (nums[mid] > target) { | |
| r = mid - 1; | |
| } else if (nums[mid] < target) { | |
| l = mid + 1; | |
| } else { | |
| r = mid; | |
| } | |
| } | |
| if (nums[l] == target) { | |
| return l; | |
| } | |
| return -1; | |
| } | |
| private int findLast(int[] nums, int target) { | |
| int l = 0; | |
| int r = nums.length - 1; | |
| while(l < r) { | |
| int mid = l + (r - l - 1) / 2 + 1; // (l + r + 1) / 2; | |
| if (nums[mid] > target) { | |
| r = mid - 1; | |
| } else if (nums[mid] > target) { | |
| l = mid + 1; | |
| } else { | |
| l = mid; | |
| } | |
| } | |
| if (nums[l] == target) { | |
| return l; | |
| } | |
| return -1; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment