File tree 3 files changed +69
-0
lines changed
solution/0900-0999/0973.K Closest Points to Origin
3 files changed +69
-0
lines changed Original file line number Diff line number Diff line change @@ -149,4 +149,32 @@ impl Solution {
149
149
150
150
<!-- solution: end -->
151
151
152
+ <!-- solution: start -->
153
+
154
+ ### Solution 2. Priority queue
155
+
156
+ <!-- tabs: start -->
157
+
158
+ #### TypeScript
159
+
160
+ ``` ts
161
+ function kClosest(points : number [][], k : number ): number [][] {
162
+ const minPQ = new MinPriorityQueue ();
163
+
164
+ for (const [x, y] of points ) {
165
+ const d = x ** 2 + y ** 2 ;
166
+ minPQ .enqueue ([x , y ], d );
167
+ }
168
+
169
+ const res: number [][] = [];
170
+ while (k -- ) res .push (minPQ .dequeue ().element );
171
+
172
+ return res ;
173
+ }
174
+ ```
175
+
176
+ <!-- tabs: end -->
177
+
178
+ <!-- solution: end -->
179
+
152
180
<!-- problem: end -->
Original file line number Diff line number Diff line change @@ -141,4 +141,32 @@ impl Solution {
141
141
142
142
<!-- solution: end -->
143
143
144
+ <!-- solution: start -->
145
+
146
+ ### Solution 2. Priority queue
147
+
148
+ <!-- tabs: start -->
149
+
150
+ #### TypeScript
151
+
152
+ ``` ts
153
+ function kClosest(points : number [][], k : number ): number [][] {
154
+ const minPQ = new MinPriorityQueue ();
155
+
156
+ for (const [x, y] of points ) {
157
+ const d = x ** 2 + y ** 2 ;
158
+ minPQ .enqueue ([x , y ], d );
159
+ }
160
+
161
+ const res: number [][] = [];
162
+ while (k -- ) res .push (minPQ .dequeue ().element );
163
+
164
+ return res ;
165
+ }
166
+ ```
167
+
168
+ <!-- tabs: end -->
169
+
170
+ <!-- solution: end -->
171
+
144
172
<!-- problem: end -->
Original file line number Diff line number Diff line change
1
+ function kClosest ( points : number [ ] [ ] , k : number ) : number [ ] [ ] {
2
+ const minPQ = new MinPriorityQueue ( ) ;
3
+
4
+ for ( const [ x , y ] of points ) {
5
+ const d = x ** 2 + y ** 2 ;
6
+ minPQ . enqueue ( [ x , y ] , d ) ;
7
+ }
8
+
9
+ const res : number [ ] [ ] = [ ] ;
10
+ while ( k -- ) res . push ( minPQ . dequeue ( ) . element ) ;
11
+
12
+ return res ;
13
+ }
You can’t perform that action at this time.
0 commit comments