Heap(medium两道题)

本文详细介绍了LeetCode上两道经典算法题的解决方案,包括寻找数组中第K大的元素及找出数组中最频繁出现的K个元素。通过桶排序等高效算法,实现优于O(nlogn)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

215. Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the
kth largest element in the sorted order, not the kth distinct element.
在这里插入图片描述
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/60294/Solution-explained

347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.
在这里插入图片描述
Note:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

Java O(n) Solution - Bucket Sort:

Idea is simple. Build a array of list to be buckets with length 1 to sort.

class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {

        List<Integer>[] bucket = new List[nums.length + 1];
        Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();

        for (int n : nums) {
            frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
        }

        for (int key : frequencyMap.keySet()) {
            int frequency = frequencyMap.get(key);
            if (bucket[frequency] == null) {
                bucket[frequency] = new ArrayList<>();
            }
            bucket[frequency].add(key);
        }

        List<Integer> res = new ArrayList<>();

        for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
            if (bucket[pos] != null) {
                res.addAll(bucket[pos]);
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值