首页 > 其他分享 >【优先队列】LeetCode 973. 最接近原点的 K 个点

【优先队列】LeetCode 973. 最接近原点的 K 个点

时间:2023-01-08 11:22:22浏览次数:53  
标签:node Node 973 个点 int queue result new LeetCode

题目链接

973. 最接近原点的 K 个点

思路

使用优先队列处理前k大问题

代码

class Solution {
    class Node{
        int x;
        int y;
        double distance;
    }

    public int[][] kClosest(int[][] points, int k) {
        int[][] result = new int[k][2];
        PriorityQueue<Node> queue = new PriorityQueue<>(new Comparator<Node>() {
            @Override
            public int compare(Node o1, Node o2) {
                return Double.compare(o2.distance, o1.distance);
            }
        });

        for(int i = 0; i < points.length; i++){
            Node node = new Node();
            node.x = points[i][0];
            node.y = points[i][1];
            node.distance = Math.sqrt(Math.pow(node.x, 2) + Math.pow(node.y, 2));
            queue.add(node);
            if(queue.size() > k){
                queue.poll();
            }
        }

        for(int i = 0; i < k; i++){
            Node node = queue.poll();
            result[i][0] = node.x;
            result[i][1] = node.y;
        }

        return result;
    }
}

标签:node,Node,973,个点,int,queue,result,new,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17034287.html

相关文章

  • LeetCode每日一题1.8
    2185.CountingWordsWithaGivenPrefixhttps://leetcode.cn/problems/counting-words-with-a-given-prefix/官方题解:https://leetcode.cn/problems/counting-words-w......
  • [C++/Java/Py/C#/Ruby/Swift/Go/Scala/Kotlin/Rust/PHP/TS/Elixir/Dart/Racket/Erlang
    目录题解地址代码cppjavapython3C#rubyswiftgolangscalakotlinrustphptypescriptelixirdartracketerlang题解地址https://leetcode.cn/problems/counting-words-with-a-g......
  • [LeetCode] 149. Max Points on a Line
    Givenanarrayof points where points[i]=[xi,yi] representsapointonthe X-Y plane,return themaximumnumberofpointsthatlieonthesamestraig......
  • leetcode-1658. 将 x 减到 0 的最小操作数
    正向双指针有点麻烦,但是能通过,先提交一下,待我学习一下其他的解法再来提交这个里面不用对opNum进行计数,可以利用left和right的位置计算出来左右两边的长度,可以省略一些,这......
  • 代码随想录day10 LeetCode20 有效的括号 1047. 删除字符串中的所有相邻重复项
     LeetCode20有效的括号 https://leetcode.cn/problems/valid-parentheses/submissions/流程为遍历每一个字符并判断是否为左括号还是有括号,若为左括号则放入栈中,若为......
  • [leetcode每日一题]1.7
    ​​1658.将x减到0的最小操作数​​难度中等给你一个整数数组 ​​nums​​ 和一个整数 ​​x​​ 。每一次操作时,你应当移除数组 ​​nums​​ 最左边或最右边......
  • 【哈希表】LeetCode 299. 猜数字游戏
    题目链接299.猜数字游戏思路建立两个哈希表分别存储secret和guess中不是bulls的数字出现次数。代码classSolution{publicStringgetHint(Stringsecret,......
  • LeetCode 103_ 二叉树的锯齿形层序遍历
    LeetCode103:二叉树的锯齿形层序遍历题目给你二叉树的根节点root,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进......
  • 【哈希表】LeetCode 350. 两个数组的交集 II
    题目链接350.两个数组的交集II思路建立两个哈希表分别统计nums1和nums2中每个数字出现的个数,然后同时遍历两个哈希表,对两个对位元素取其最小值count,将count数......
  • 【哈希表】LeetCode 49. 字母异位词分组
    题目链接49.字母异位词分组思路如果一对字符串是字母异位词,那么他们经过排序之后,应该是相等的。利用这一特点,我们通过哈希表建立排序后字符串到原字符串列表的映射,不......