0%

K Closest Points to Origin

Question

We have a list of points on the plane. Find the K closest points to the origin (0, 0).

(Here, the distance between two points on a plane is the Euclidean distance.)

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)

Example 1:

Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
@priorityQueue to add smallest distance, if size > k, poll the larger one.
*/
public int[][] kClosest(int[][] points, int K) {
Queue<int[]> maxHeap = new PriorityQueue<>( (a,b) -> b[2] - a[2]);

for (int[] point : points) {
int[] distance = new int[3];
distance[0] = point[0];
distance[1] = point[1];
distance[2] = point[0] * point[0] + point[1] * point[1];
if (maxHeap.size() == K) {
if (distance[2] < maxHeap.peek()[2]) {
int[] pollDistance = maxHeap.poll();
maxHeap.offer(distance);
}
}else {
maxHeap.offer(distance);
}
}
int[][] temp = new int[K][2];
int index = 0;
for (int[] result : maxHeap) {
temp[index][0] = result[0];
temp[index++][1] = result[1];
}
return temp;
}