# 347. Top K Frequent Elements

[Given a non-empty array of integers, return the **k** most frequent elements.](https://leetcode.com/problems/top-k-frequent-elements/)

```java
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        // maxmium heap
        Map<Integer, Integer> memo = new HashMap<>();
        for(int value : nums){
            memo.put(value, memo.getOrDefault(value, 0)+1);
        }
        int[] res = new int[k];
        int index = 0;
        // maxium heap
        Queue<Integer> maxHeap = new PriorityQueue<>((a,b)->memo.get(b)-memo.get(a));
        for(Integer key : memo.keySet()){
            maxHeap.add(key);
            if(maxHeap.size()==memo.size()-k+1){
                res[index++]=maxHeap.poll(); 
            }
        }
        return res;
    }
}
```


---

# 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://ucan.gitbook.io/notes/tree/untitled.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.
