티스토리 뷰
BST
이미 sorted 된 데이터의 경우, BST를 이용해 O(log n)의 시간복잡도로 타겟을 찾을 수 있다.
34. Find First and Last Position of Element in Sorted Array
Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
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]
const searchRange = function (nums, target) {
const { length } = nums;
let firstIndex = 0;
let lastIndex = length - 1;
while (firstIndex <= lastIndex) {
const midIndex = Math.floor((firstIndex + lastIndex) / 2);
if (nums[midIndex] === target) {
firstIndex = midIndex;
lastIndex = midIndex;
break;
}
if (nums[midIndex] < target) {
//타겟이 더 크므로 뒷부분에서 탐색
firstIndex = midIndex + 1;
} else {
lastIndex = midIndex - 1;
}
}
// while문을 끝까지 순회 했으나 target을 못찾은 경우
if (firstIndex > lastIndex) {
return [-1, -1];
}
//중간에 break되어서 나왔을 경우, 앞뒤로 같은 값 있는지 탐색
while (nums[firstIndex - 1] === target) firstIndex--;
while (nums[lastIndex + 1] === target) lastIndex++;
return [firstIndex, lastIndex];
};
출처 : leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
'공부 > JS' 카테고리의 다른 글
[JS] Deep Equality checking of Two Objects (0) | 2020.09.20 |
---|---|
[JS/알고리즘] Sort Colors : Dutch national flag problem (0) | 2020.09.07 |
[JS/알고리즘] Merge Two Sorted Lists (0) | 2020.09.07 |
[JS] Promise.all()은 병렬일까 직렬일까🤔 (1) | 2020.08.22 |
[JS] Prevent Stack Overflow (0) | 2020.08.06 |
댓글