比较器和PriorityQueue

阿米特·尼吉(Amit Negi):
        int points[][] = { { 0, 1 }, { 1, 0 }, {3,3},{5,-1},{-2,4}}, k = 2;
        Queue<int[]> pq = new PriorityQueue<>((a, b) -> ((b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1])));
        for (int[] e : points) {
            pq.add(e);`
             if (pq.size() > k)
                pq.remove();
        }

有人可以向我解释此代码的工作原理吗?谢谢你的帮助

帕特里克·陈(PatrickChen):

使用PriorityQueue排序int []的代码,仅选择top2。比较器功能是:

(a, b) -> ((b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1])) //smaller item will be sort first

例如:{0,1},{1,0},它们将相等,{3,3},{5,-1},{5,-1}会更大。

for (int[] e : points) {
            pq.add(e); // put the int[] into the queue, queue will sort all items
             if (pq.size() > k) 
                pq.remove(); // if the size of the queue exceed, remove the last item in the queue (the more big item)
        }

代码的结果将是前2个最小的结果。{1,0}和{0,1}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章