优先级队列实现以及应用

队列

队列是一种受限的线性表,对于大部分线性表而言,通常除了第一个和最后一个数据元素之外,其他数据元素都是首尾相接的。

  • 先来的元素在队首,后来的只能在末尾,不允许插队。
  • 只能在表的前端进行删除,后端进行插入。FIFO

优先级队列

  • 优先级队列不再遵循FIFO的规则,而是按照自定义规则(优先级高低)将对应元素取出队列,比如取出优先级高的元素,或者淘汰优先级低的元素。
  • 实现方式两种:入队的时候找准位置,或者出队的时候找准位置
  • Java中的PriorityBlockingQueue是基于PriorityQueue的再次包装,都是基于堆数据结构实现。
  • 数组实现方式

代码

public class KSmallestPairs {
    public static List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        PriorityQueue<int[]> que = new PriorityQueue<>((a, b) -> a[0] + a[1] - b[0] - b[1]);
        List<List<Integer>> res = new ArrayList<>();
        //边界限制
        if (nums1.length == 0 || nums2.length == 0 || k == 0) {
            return res;
        }
        for (int i = 0; i < nums1.length && i < k; i++) {
            que.offer(new int[]{nums1[i], nums2[0], 0});
        }

        //
        while (k-- > 0 && !que.isEmpty()) {
            int[] cur = que.poll();
            res.add(Arrays.asList(cur[0], cur[1]));
            if (cur[2] == nums2.length - 1) continue;//????
            que.offer(new int[]{cur[0], nums2[cur[2] + 1], cur[2] + 1});
        }
        return res;
    }

    public static void main(String[] args) {

        List<List<Integer>> result = kSmallestPairs(new int[]{1, 7}, new int[]{2, 4, 6}, 3);
        result.forEach(System.out::print);

        //test         PriorityQueue
        PriorityQueue<int[]> que = new PriorityQueue<>((a, b) -> a[0] + a[1] - b[0] - b[1]);

        que.offer(new int[]{5, 5, 1});
        que.offer(new int[]{6, 6, 9});
        que.poll();//优先级越高,越先弹出。优先级从0-n 逐级上升
        System.out.println(Arrays.deepToString(que.toArray()));


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值