LeetCode347_前 K 个高频元素_排序_堆排序_非递归写法

该题与LeetCode215题十分类似

B站视频地址:【LeetCode215_数组中的第K个最大元素_排序_堆排序_非递归写法】 LeetCode215_数组中的第K个最大元素_排序_堆排序_非递归写法

class Solution {
    Map<Integer, Integer> map = new HashMap<>();

    public int[] topKFrequent(int[] nums, int k) {
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        int[] heap = new int[k];
        int count = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (count < k) {
                heap[count] = entry.getKey();
            }
            count++;
            if (count == k) {
                buildMinHeap(heap);
            }
            if (count > k) {
                // 调整小根堆
                if (entry.getValue() > map.get(heap[0])) {
                    heap[0] = entry.getKey();
                    heapAdjust(heap, 0, k);
                }
            }
        }
        return heap;
    }

    public void buildMinHeap(int[] heap) {
        int len = heap.length;
        for (int i = len / 2 - 1; i >= 0; i--) {
            heapAdjust(heap, i, len);
        }
    }

    public void heapAdjust(int[] heap, int root, int heapLen) {
        int temp = heap[root];
        for (int i = (root << 1) + 1; i < heapLen; i = (i << 1) + 1) {
            if (i < heapLen - 1 && map.get(heap[i]) > map.get(heap[i + 1])) {
                i++;
            }
            if (map.get(temp) <= map.get(heap[i])) {
                break;
            } 
            heap[root] = heap[i];
            root = i;
        }
        heap[root] = temp;
    }

    public void swap(int[] heap, int a, int b) {
        if (heap[a] != heap[b]) {
            int temp = heap[a];
            heap[a] = heap[b];
            heap[b] = temp;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值