Created
February 10, 2020 15:28
-
-
Save luojiyin1987/a1b07efdfbba0e61051eabf4ae1f8205 to your computer and use it in GitHub Desktop.
Find First and Last Position of Element in Sorted 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
| /** | |
| * @param {number[]} nums | |
| * @param {number} target | |
| * @return {number[]} | |
| */ | |
| var searchRange = function(nums, target) { | |
| const left = lowerBound(nums, target); | |
| const right = upperBound(nums, target); | |
| if (left < right) { | |
| return [left, right - 1]; | |
| } | |
| return [-1, -1]; | |
| }; | |
| function lowerBound(arr, target) { | |
| let left = 0; | |
| let right = arr.length; | |
| while (left < right) { | |
| const mid = Math.floor((left + right) / 2); | |
| if (target > arr[mid]) { | |
| left = mid + 1; | |
| } else { | |
| right = mid; | |
| } | |
| } | |
| return left; | |
| } | |
| function upperBound(arr, target) { | |
| let left = 0; | |
| let right = arr.length; | |
| while (left < right) { | |
| const mid = Math.floor((left + right) / 2); | |
| if (target >= arr[mid]) { | |
| left = mid + 1; | |
| } else { | |
| right = mid; | |
| } | |
| } | |
| return left; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment