LeetCode #347. 前 K 个高频元素

发布: (2026年1月31日 GMT+8 17:49)
1 min read
原文: Dev.to

Source: Dev.to

复杂度分析

  • 时间复杂度: O(n log n)(主要由排序决定)
  • 空间复杂度: O(n),用于 HashMap 和 List

解法

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        List list = new ArrayList<>(map.keySet());
        list.sort((a, b) -> Integer.compare(map.get(b), map.get(a)));

        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = list.get(i);
        }
        return result;
    }
}
Back to Blog

相关文章

阅读更多 »