LeetCode973_最接近原点的 K 个点_排序_堆排序_经典堆排序写法

解题思路

image.png

比优先队列快,可能是最快的堆排序,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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值