forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path937-K-Closest-Points-To-Origin.js
97 lines (75 loc) · 2.45 KB
/
937-K-Closest-Points-To-Origin.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* https://leetcode.com/problems/k-closest-points-to-origin/
* Time O(N * log(N)) | Space O(K)
* @param {number[][]} points
* @param {number} k
* @return {number[][]}
*/
var kClosest = function(points, K) {
const distance = ([x, y]) => (x * x) + (y * y);
points.sort((a, b) => distance(a) - distance(b));
return points.slice(0, K);
};
/**
* https://leetcode.com/problems/k-closest-points-to-origin/
* Time O(log(K)) | Space O(K)
* @param {number[][]} points
* @param {number} k
* @return {number[][]}
*/
var kClosest = function(points, K) {
const [ left, right ] = [ 0, (points.length - 1) ];
quickSelect(points, K, left, right);
return points.slice(0, K)
};
const quickSelect = (points, target, left, right) => {
const mid = getMid(points, left, right);
const isTarget = mid === (target - 1);
if (isTarget) return;
const isTargetGreater = mid < (target - 1);
if (isTargetGreater) quickSelect(points, target, (mid + 1), right);
const isTargetLess = (target - 1) < mid;
if (isTargetLess) quickSelect(points, target, left, (mid - 1));
}
const swap = (points, left, right) => [ points[left], points[right] ] = [ points[right], points[left] ];
const squareRoot = ([ x, y ]) => ((x * x) + (y * y));
const getMid = (points, left, right) => {
let mid = left;
while (left < right) {
const [ leftDistance, rightDistance ] = [ squareRoot(points[left]), squareRoot(points[right]) ];
const canSwapMid = leftDistance <= rightDistance
if (canSwapMid) {
swap(points, left, mid);
mid++;
}
left++;
}
swap(points, mid, right);
return mid;
}
/**
* https://leetcode.com/problems/k-closest-points-to-origin/
* Time O(N * log(K)) | Space O(K)
* @param {number[][]} points
* @param {number} k
* @return {number[][]}
*/
var kClosest = function(points, k) {
const maxHeap = new MaxPriorityQueue({ priority: (point) => distance(point) })
for (const point of points) {
const isUnderCapacity = maxHeap.size() < k;
if (isUnderCapacity) {
maxHeap.enqueue(point);
continue;
}
const isCloser = distance(point) < distance(maxHeap.front().element);
if (isCloser) {
maxHeap.dequeue();
maxHeap.enqueue(point);
}
}
return maxHeap
.toArray()
.map(({ element }) => element);
}
const distance = ([ x, y ]) => (x * x) + (y * y);