We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1516886 commit 320f26dCopy full SHA for 320f26d
solution/0900-0999/0973.K Closest Points to Origin/Solution2.ts
@@ -1,13 +1,11 @@
1
function kClosest(points: number[][], k: number): number[][] {
2
- const minPQ = new MinPriorityQueue();
3
-
+ const maxQ = new MaxPriorityQueue();
4
for (const [x, y] of points) {
5
- const d = x ** 2 + y ** 2;
6
- minPQ.enqueue([x, y], d);
+ const dist = x * x + y * y;
+ maxQ.enqueue([x, y], dist);
+ if (maxQ.size() > k) {
7
+ maxQ.dequeue();
8
+ }
9
}
- const res: number[][] = [];
10
- while (k--) res.push(minPQ.dequeue().element);
11
12
- return res;
+ return maxQ.toArray().map(item => item.element);
13
0 commit comments