612. k closest points

explanation

  1. 选最小的k个,维持个size为k的maxheap
  2. comparator a - b 是 最小堆
  3. euclidean distance: (a.x-b.x)^2 + (a.y-b.y)^2
  4. PriorityQueue 是completed binary tree

code

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* } * Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/

public class {

* @param points: a list of points
* @param origin: a point
* @param k: An integer
* @return: the k closest points
*/
public Point[] kClosest(Point[] points, Point origin, int k) {
// write your code here
// max heap
PriorityQueue<Point> pq = new PriorityQueue<Point>(k, new Comparator<Point>() {
public int compare(Point a, Point b) {
int diff = getDistance(b, origin) - getDistance(a, origin);
if (diff == 0) {
diff = b.x - a.x;
}
if (diff == 0) {
diff = b.y - a.y;
}
return diff;

}

}
);
Point[] result = new Point[k];

for (int i = 0; i < points.length; i++) {
pq.offer(points[i]);
if (pq.size() > k) {
pq.poll();
}
}
while (!pq.isEmpty()) {
result[--k] = pq.poll(); // 先减 --k!!!
}
return result;

}
private int getDistance(Point a, Point b) {
return (a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y);
}
}

complexity

  1. time: O(nlog(k))
  2. space: O(n)