0
点赞
收藏
分享

微信扫一扫

【数据结构】堆

一枚路过的程序猿 2022-04-23 阅读 62
数据结构

public static int majorityElement3(int[] nums) {
        int len = (nums.length + 1) / 2;
  			//定义大根堆,堆顶最大,求top-k小问题
        PriorityQueue<Integer> queue = new PriorityQueue<>(len, Comparator.comparingLong(item -> -item));
        for (int num : nums) {
            queue.offer(num);
            if (queue.size() > len) {
                queue.poll();
            }
        }
        return queue.poll();
    }
//定义小根堆,堆顶最小,求top-k大问题  默认小根堆--求最大
        PriorityQueue<Integer> queue = new PriorityQueue<>(len, Comparator.comparingLong(item -> item));

//定义大根堆,堆顶最大,求top-k小问题
        PriorityQueue<Integer> queue = new PriorityQueue<>(len, Comparator.comparingLong(item -> -item));
举报

相关推荐

数据结构——堆

数据结构--堆

数据结构-堆

数据结构:堆

堆(数据结构)

数据结构---堆---简单

0 条评论