MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / kClosest

Method kClosest

java/0973-k-closest-points-to-origin.java:7–24  ·  view source on GitHub ↗
(int[][] points, int k)

Source from the content-addressed store, hash-verified

5class Solution {
6
7 public int[][] kClosest(int[][] points, int k) {
8 PriorityQueue<int[]> q = new PriorityQueue<>((a, b) ->
9 Integer.compare(
10 (a[0] * a[0] + a[1] * a[1]),
11 (b[0] * b[0] + b[1] * b[1])
12 )
13 );
14 for (int[] point : points) {
15 q.add(point);
16 }
17 int[][] ans = new int[k][2];
18 for (int i = 0; i < k; i++) {
19 int[] cur = q.poll();
20 ans[i][0] = cur[0];
21 ans[i][1] = cur[1];
22 }
23 return ans;
24 }
25}
26
27//This approach is a sightly optimized approach here we can use a max heap and maintain its size as k.

Callers

nothing calls this directly

Calls 4

compareMethod · 0.45
addMethod · 0.45
sizeMethod · 0.45
removeMethod · 0.45

Tested by

no test coverage detected