[JS] Find First and Last Position of Element in Sorted Array
2022. 8. 4. 13:18
🔒 문제 (LeetCode 34)
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Constraints:
- 0 <= nums.length <= 105
- -109 <= nums[i] <= 109
- nums is a non-decreasing array.
- -109 <= target <= 109
🌊 입출력
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 3:
Input: nums = [], target = 0
Output: [-1,-1]
🔑 해결
🌌 알고리즘 - 이분탐색
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {
let result = [];
let l = 0;
let r = nums.length - 1;
while(l < r) {
let mid = l + r >>> 1;
if(nums[mid] < target) {
l = mid + 1;
} else r = mid;
}
if(nums[r] !== target) return [-1, -1];
else result.push(r);
while(nums[r] === target) r++;
result.push(r-1);
return result;
};
'코딩테스트 (JS) > 이분탐색' 카테고리의 다른 글
[JS] Search a 2D Matrix (0) | 2022.08.04 |
---|---|
[JS] Search in Rotated Sorted Array (0) | 2022.08.04 |
[JS] Search Insert Position (0) | 2022.07.29 |
[JS] First Bad Version (0) | 2022.07.29 |
[JS] 선입 선출 스케줄링 (0) | 2022.07.13 |