解题思路
比优先队列快,可能是最快的堆排序,16ms
代码
class Solution {
public int[][] kClosest(int[][] points, int k) {
int[][] result = new int[k][2];
buildMinHeap(points);
int len = points.length;
for (int i = points.length - 1; i > points.length - k - 1; i--) {
swap(points, 0, i);
len--;
heapAdjust(points, 0, len);
}
System.arraycopy(points, points.length - k, result, 0, k);
return result;
}
private void buildMinHeap(int[][] heap) {
int len = heap.length;
for (int i = len / 2 - 1; i >= 0; i--) {
heapAdjust(heap, i, len);
}
}
private void heapAdjust(int[][] heap, int root, int heapLen) {
int[] temp = heap[root];
for (int i = (root << 1) + 1; i < heapLen; i = (i << 1) + 1) {
if (i < heapLen - 1 && distance(heap[i + 1][0], heap[i + 1][1]) < distance(heap[i][0], heap[i][1])) {
i++;
}
if (distance(temp[0], temp[1]) <= distance(heap[i][0], heap[i][1])) {
break;
}
heap[root] = heap[i];
root = i;
}
heap[root] = temp;
}
private int distance(int x, int y) {
return x * x + y * y;
}
private void swap(int[][] heap, int a, int b) {
int[] temp = heap[a];
heap[a] = heap[b];
heap[b] = temp;
}
}