# 347. Top K Frequent Elements

> 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(n log n), where n is the array's size.

## Thoughts

找出现频率最高的K个元素。前x的k个=>heap。要求最大的k个，维持一个大小为k的min heap，每次遍历时当超过k个时，把最小的踢出去，剩下的的就是最大的K个。

## Code

```cpp
/*
 * @lc app=leetcode id=347 lang=cpp
 *
 * [347] Top K Frequent Elements
 */

// @lc code=start
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> freq;
        const auto cmp = [](auto &a, auto &b) {
            return a.first > b.first;
        };
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);
        for (const auto num : nums) ++freq[num];
        for (const auto &p : freq) {
            pq.push({p.second, p.first});
            if (pq.size() > k) {
                pq.pop();
            }
        }
        vector<int> res(k, 0);
        for (int i = k - 1; i >= 0; --i) {
            res[i] = pq.top().second;
            pq.pop(); 
        }
        return res;
    }
};
// @lc code=end


```

```java
class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], 1);
            } else {
                map.put(nums[i], map.get(nums[i]) + 1);
            }
        }

        PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(
            new Comparator<Map.Entry<Integer, Integer>>() {
                @Override
                public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) {
                    return a.getValue() - b.getValue();
                }
            }
        );

        for (Map.Entry e : map.entrySet()) {
            pq.add(e);
            if (pq.size() > k) {
                pq.poll();
            }
        }

        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < k; ++i) {
            Map.Entry e = pq.poll();
            res.add(0, (int)e.getKey());
        }

        return res;
    }
}
```

## Analysis

时间复杂度O(n + klgn).


---

# Agent Instructions: 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://hao-fu-1.gitbook.io/oj/heap/xuan-chu-chu-xian-pin-lv-zui-gao-de-k-ge/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.
