-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0658-find-k-closest-elements.js
More file actions
46 lines (41 loc) · 1.35 KB
/
0658-find-k-closest-elements.js
File metadata and controls
46 lines (41 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Find K Closest Elements
* Time Complexity: O(logN + K)
* Space Complexity: O(K)
*/
var findClosestElements = function (arr, k, x) {
let initialLeftPosition = 0;
let initialRightPosition = arr.length - 1;
let insertionCandidateIndex = 0;
while (initialLeftPosition <= initialRightPosition) {
let midSearchIndex = Math.floor(
initialLeftPosition + (initialRightPosition - initialLeftPosition) / 2,
);
if (arr[midSearchIndex] >= x) {
insertionCandidateIndex = midSearchIndex;
initialRightPosition = midSearchIndex - 1;
} else {
initialLeftPosition = midSearchIndex + 1;
}
}
let leftExpansionPointer = insertionCandidateIndex - 1;
let rightExpansionPointer = insertionCandidateIndex;
let currentWindowSize = 0;
while (currentWindowSize < k) {
if (leftExpansionPointer < 0) {
rightExpansionPointer++;
} else if (rightExpansionPointer >= arr.length) {
leftExpansionPointer--;
} else {
let leftValueDifference = Math.abs(arr[leftExpansionPointer] - x);
let rightValueDifference = Math.abs(arr[rightExpansionPointer] - x);
if (leftValueDifference <= rightValueDifference) {
leftExpansionPointer--;
} else {
rightExpansionPointer++;
}
}
currentWindowSize++;
}
return arr.slice(leftExpansionPointer + 1, rightExpansionPointer);
};