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

解题思路

手撕快排,比较符合编码规范,有良好编码风格的快排。速度快得不谈
image.png

代码

class Solution {
    public int[][] kClosest(int[][] points, int k) {
        quickSort(points, 0, points.length - 1, k);
        return Arrays.copyOfRange(points, 0, k);
    }

    private void quickSort(int[][] points, int left, int right, int k) {
        if (left < right) {
            int pviotPosition = partition(points, left, right);
            if (pviotPosition == k - 1) {
                return;
            } else if (pviotPosition > k - 1) {
                quickSort(points, left, pviotPosition - 1, k);
            } else {
                quickSort(points, pviotPosition + 1, right, k);
            }
        }
    }

    private int partition(int[][] points, int left, int right) {
        swap(points, left, (left + right) / 2);
        int[] pviotNum = points[left];
        int distance = distance(pviotNum);
        while (left < right) {
            while (left < right && distance(points[right]) > distance) {
                right--;
            }
            points[left] = points[right];
            while (left < right && distance(points[left]) <= distance) {
                left++;
            }
            points[right] = points[left];
        }
        points[left] = pviotNum;
        return left;
    }

    private int distance(int[] point) {
        return point[0] * point[0] + point[1] * point[1];
    }

    private void swap(int[][] points, int a, int b) {
        int[] temp = points[a];
        points[a] = points[b];
        points[b] = temp;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值