# 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.

```cpp
vector<int> topKFrequent(vector<int>& nums, int k) {
    vector<int> most_freq;
    unordered_map<int, int> hashmap;

    for (int i : nums) {
        // not found, insert new number
        if (hashmap.find(i) == hashmap.end()) {
            hashmap.insert({ { i },{ 1 } });
        }

        // found update frequency
        hashmap.find(i)->second++;
    }

    for (int i = 0; i < k; i++) {
        int max = 0;
        int key = 0;
        for (auto &i : hashmap) {
            if (i.second > max) {
                max = i.second;
                key = i.first;
            }
        }
        hashmap.erase(hashmap.find(key));
        most_freq.push_back(key);
    }

    return most_freq;
}
```


---

# 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://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/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.
