美文网首页
LeetCode 第 973 题:最接近原点的 K 个点

LeetCode 第 973 题:最接近原点的 K 个点

作者: 放开那个BUG | 来源:发表于2023-03-11 16:18 被阅读0次

1、前言

题目描述

2、思路

就是一般的求最大k个数和最小k个数的思路

3、代码

class Solution {
    public int[][] kClosest(int[][] points, int k) {
        PriorityQueue<int[]> maxHeap = new PriorityQueue<>((o1, o2) -> distance(o2) - distance(o1));

        for(int i = 0; i < k; i++){
            maxHeap.offer(points[i]);
        }

        for(int i = k; i < points.length; i++){
            if(distance(points[i]) < distance(maxHeap.peek())){
                maxHeap.poll();
                maxHeap.offer(points[i]);
            }
        }

        int[][] res = new int[k][2];
        for(int i = 0; i < k; i++){
            res[i] = maxHeap.poll();
        }

        return res;
    } 


    private int distance(int[] a){   
        return (int)(Math.pow(a[0], 2) + Math.pow(a[1], 2));
    }
}

相关文章

网友评论

      本文标题:LeetCode 第 973 题:最接近原点的 K 个点

      本文链接:https://www.haomeiwen.com/subject/qwskurtx.html