LeetCode 347. 前 K 个高频元素

题目:

力扣

题解一:

  1. 用map统计每个数字出现的次数
  2. 遍历一边map找出次数第k大的数
  3. 再遍历一边map找出次数大于等于k的所有num

时间复杂度:O(nlogn)

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

        List countList = new ArrayList<>(nums.length);
        countMap.forEach((num, count) -> countList.add(count));
        countList.sort(Comparator.comparing(Integer::intValue).reversed());

        int targetK = countList.get(k-1);
        List resultList = new ArrayList<>(nums.length);
        countMap.forEach((num, count) -> {
            if (count >= targetK) {
                resultList.add(num);
            }
        });

        int[] resultArray = new int[resultList.size()];
        for (int i = 0; i < resultList.size() && i < k; i++) {
            resultArray[i] = resultList.get(i);
        }

        return resultArray;
    }

题解二:

利用最小堆维护一个只包含k个元素的集合,每次弹出最小的元素,最终堆里剩下的就是前k个最大元素,时间复杂度:O(nlogk)

        Map countMap = new HashMap<>(nums.length);
        for (int num : nums) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }

        Set> entries = countMap.entrySet();
        PriorityQueue> queue = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue));

        for (Map.Entry entry : entries) {
            queue.offer(entry);
            if (queue.size() > k) {
                queue.poll();
            }
        }

        int[] resultArray = new int[queue.size()];
        for (int i = 0; i < k && !queue.isEmpty(); i++) {
            resultArray[i] = queue.poll().getKey();
        }

        return resultArray;

你可能感兴趣的:(LeetCode,leetcode,堆,优先队列,前k个高频元素)