# 347.Top-K-Frequent-Elements

## 347. Top K Frequent Elements

## 题目地址

<https://leetcode.com/problems/top-k-frequent-elements/>

## 题目描述

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

Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:
Input: nums = [1], k = 1
Output: [1]
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.
```

## 代码

### Approach 1: Heap

**Complexity Analysis**

* Time complexity : O(*N\_log(\_k*)). The complexity of \`Counter method is O(*N*). To build a heap and output list takes O(*N\_log(\_k*)). Hence the overall complexity of the algorithm is O(*N*+*N\_log(\_k*)=O(*N\_log(\_k*).
* Space complexity : O(*N*) to store the hash map.

```java
class Solution {
  public List<Integer> topKFrequent(int[] nums, int k) {
    HashMap<Integer, Integer> count = new HashMap();
    for (int n : nums) {
      count.put(n, count.getOrDefault(n, 0) + 1);
    }

    PriorityQueue<Integer> heap = new PriorityQueue<Integer>((n1, n2) -> count.get(n1) - count.get(n2));

    for (int n : count.keySet()) {
      heap.add(n);
      if (heap.size() > k) 
        heap.poll();
    }

    List<Integer> ans = new LinkedList();
    while (!heap.isEmpty()) {
      ans.add(heap.poll());
    }
    Collections.reverse(ans);
    return ans;
    }
}
```


---

# 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://wentao-shao.gitbook.io/leetcode/array/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.
