File tree Expand file tree Collapse file tree 1 file changed +13
-11
lines changed Expand file tree Collapse file tree 1 file changed +13
-11
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int [][] kClosest (int [][] points , int K ) {
3
3
if (points == null || points .length == 0 ) {
4
- return points ;
4
+ return new int [][] {} ;
5
5
}
6
6
7
- PriorityQueue <int []> pq = new PriorityQueue <>((a , b ) -> a [1 ] - b [1 ]);
7
+ List <int []> result = new ArrayList <>();
8
+ PriorityQueue <int []> pq = new PriorityQueue <>(
9
+ (p1 , p2 ) -> (p2 [0 ] * p2 [0 ] + p2 [1 ] * p2 [1 ]) - (p1 [0 ] * p1 [0 ] + p1 [1 ] * p1 [1 ]));
8
10
9
- for (int i = 0 ; i < points .length ; i ++) {
10
- int distance = (Math .abs (points [i ][0 ]) * Math .abs (points [i ][0 ]))
11
- + (Math .abs (points [i ][1 ]) * Math .abs (points [i ][1 ]));
12
- pq .offer (new int [] { i , distance });
11
+ for (int [] pair : points ) {
12
+ pq .offer (pair );
13
+
14
+ if (pq .size () > K ) {
15
+ pq .poll ();
16
+ }
13
17
}
14
18
15
- ArrayList <int []> result = new ArrayList <>();
16
- while (K > 0 ) {
17
- result .add (points [pq .poll ()[0 ]]);
18
- --K ;
19
+ while (K -- > 0 ) {
20
+ result .add (pq .poll ());
19
21
}
20
22
21
- return result .toArray (new int [result . size () ][]);
23
+ return result .toArray (new int [0 ][]);
22
24
}
23
25
}
You can’t perform that action at this time.
0 commit comments