The simplest way that I can think to solve this problem is using a PriorityQueue:

    public int[][] kClosest(int[][] points, int k) {
        PriorityQueue<int[]> queue = new PriorityQueue<>((a,b)->a[0]*a[0]+a[1]*a[1]-b[0]*b[0]-b[1]*b[1]);
        for(int[] point: points){
            queue.offer(point);
        }
        int[][]  res = new int[k][2];
        for (int i=0;i<k;i++){
            int[] point = queue.poll();
            res[i]=point;
        }
        return res;
    }

 

posted on 2022-02-08 14:10  阳光明媚的菲越  阅读(19)  评论(0编辑  收藏  举报