> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/heap/347-top-k-frequent-elements.md).

# 347    Top K Frequent Elements

## 347. [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/description/)

## 1. Question

Given a non-empty array of integers, return the**k**most frequent elements.

For example,\
Given`[1,1,1,2,2,3]`and k = 2, return`[1,2]`.

**Note:**

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

## 2. Implementation

**(1) Bucket Sort**

```java
class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        List<Integer> res = new ArrayList<>();

        if (nums.length == 0 || k <= 0) {
            return res;
        }

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

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

        List<Integer>[] bucket = new List[nums.length + 1];

        for (int key : map.keySet()) {
            int freq = map.get(key);

            if (bucket[freq] == null) {
                bucket[freq] = new ArrayList<>();
            }
            bucket[freq].add(key);
        }

        for (int i = nums.length; i >= 0 && res.size() < k; i--) {
            if (bucket[i] != null) {
                res.addAll(bucket[i]);
            }
        }
        return res;
    }
}
```

**(2) Heap**

```java
class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        List<Integer> res = new ArrayList<>();

        if (nums == null || nums.length == 0) {
            return res;
        }

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

        PriorityQueue<NumInfo> minHeap = new PriorityQueue<>();

        for (int key : map.keySet()) {
            minHeap.add(new NumInfo(key, map.get(key)));

            if (minHeap.size() > k) {
                minHeap.remove();
            }
        }

        while (!minHeap.isEmpty()) {
            res.add(0, minHeap.remove().val);
        }
        return res;
    }

    class NumInfo implements Comparable<NumInfo> {
        int val;
        int freq;

        public NumInfo(int val, int freq) {
            this.val = val;
            this.freq = freq;
        }

        public int compareTo(NumInfo that) {
            return this.freq - that.freq;
        }
    }
}
```

## 3. Time & Space Complexity

**Bucket Sort**: 时间复杂度O(n), 空间复杂度O(n)

**Heap:** 时间复杂度O(n + nlogk), 空间复杂度O(n)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/heap/347-top-k-frequent-elements.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
