Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

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

&nbsp;
Constraints:


	1 &lt;= nums.length &lt;= 105
	-104 &lt;= nums[i] &lt;= 104
	k is in the range [1, the number of unique elements in the array].
	It is guaranteed that the answer is unique.


&nbsp;
Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        return [i[0] for i in Counter(nums).most_common(k)]
class Solution {
	public int[] topKFrequent(int[] nums, int k) {
		Map<Integer, Integer> map = new HashMap<>();

		for (int num : nums) {        
			map.merge(num, 1, Integer::sum);
		}

		return map.entrySet()
			.stream()
			.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
			.map(Map.Entry::getKey)
			.mapToInt(x -> x)
			.limit(k)
			.toArray();
	}
}
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> map;
        for(int num : nums){
            map[num]++;
        }
        
        vector<int> res;
        // pair<first, second>: first is frequency,  second is number
        priority_queue<pair<int,int>> pq; 
        for(auto it = map.begin(); it != map.end(); it++){
            pq.push(make_pair(it->second, it->first));
            if(pq.size() > (int)map.size() - k){
                res.push_back(pq.top().second);
                pq.pop();
            }
        }
        return res;
    }
};
var topKFrequent = function(nums, k) {
  let store = {};
    for(let i=0;i<nums.length;i++){
        store[nums[i]] = store[nums[i]]+1||1
    }
    //returns an array of keys in sorted order
    let keyArr = Object.keys(store).sort((a,b)=>store[a]-store[b])
    let arrLength = keyArr.length;
    let slicedArr = keyArr.slice(arrLength-k,arrLength)
    return slicedArr
};
Top K Frequent Elements