Skip to content

Commit 3a5bb46

Browse files
authored
Update 973-k-closest-points-to-origin.js
1 parent d275406 commit 3a5bb46

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

973-k-closest-points-to-origin.js

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,96 @@ function swap(arr, i, j) {
3939
function compare(p1, p2) {
4040
return p1[0] * p1[0] + p1[1] * p1[1] - p2[0] * p2[0] - p2[1] * p2[1]
4141
}
42+
43+
44+
// another
45+
46+
/**
47+
* @param {number[][]} points
48+
* @param {number} K
49+
* @return {number[][]}
50+
*/
51+
const kClosest = (points, K) => {
52+
const pq = new PriorityQueue(
53+
(p1, p2) => p1[0] * p1[0] + p1[1] * p1[1] > p2[0] * p2[0] + p2[1] * p2[1]
54+
)
55+
for (let p of points) {
56+
pq.push(p)
57+
if (pq.size() > K) {
58+
pq.pop()
59+
}
60+
}
61+
const res = new Array(K)
62+
while (K > 0) {
63+
res[--K] = pq.pop()
64+
}
65+
return res
66+
}
67+
68+
class PriorityQueue {
69+
constructor(comparator = (a, b) => a > b) {
70+
this.heap = []
71+
this.top = 0
72+
this.comparator = comparator
73+
}
74+
size() {
75+
return this.heap.length
76+
}
77+
isEmpty() {
78+
return this.size() === 0
79+
}
80+
peek() {
81+
return this.heap[this.top]
82+
}
83+
push(...values) {
84+
values.forEach((value) => {
85+
this.heap.push(value)
86+
this.siftUp()
87+
})
88+
return this.size()
89+
}
90+
pop() {
91+
const poppedValue = this.peek()
92+
const bottom = this.size() - 1
93+
if (bottom > this.top) {
94+
this.swap(this.top, bottom)
95+
}
96+
this.heap.pop()
97+
this.siftDown()
98+
return poppedValue
99+
}
100+
replace(value) {
101+
const replacedValue = this.peek()
102+
this.heap[this.top] = value
103+
this.siftDown()
104+
return replacedValue
105+
}
106+
107+
parent = (i) => ((i + 1) >>> 1) - 1
108+
left = (i) => (i << 1) + 1
109+
right = (i) => (i + 1) << 1
110+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
111+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
112+
siftUp = () => {
113+
let node = this.size() - 1
114+
while (node > this.top && this.greater(node, this.parent(node))) {
115+
this.swap(node, this.parent(node))
116+
node = this.parent(node)
117+
}
118+
}
119+
siftDown = () => {
120+
let node = this.top
121+
while (
122+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
123+
(this.right(node) < this.size() && this.greater(this.right(node), node))
124+
) {
125+
let maxChild =
126+
this.right(node) < this.size() &&
127+
this.greater(this.right(node), this.left(node))
128+
? this.right(node)
129+
: this.left(node)
130+
this.swap(node, maxChild)
131+
node = maxChild
132+
}
133+
}
134+
}

0 commit comments

Comments
 (0)