347.Top K Frequent Elements
1.Description(Medium)
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( nlogn), where n is the array's size.
Subscribe to see which companies asked this question.
Hide Tags
2.Code
这个题跟top k frequent words很像,区别是那道题是arrays of strings, 本题是arrays of int.
用一个hashmap和一个PriorityQueue<Map.Entry<Integer,Integer>> 来解决。
word那道题用了一个class 来封装string 和frequency,本题直接用map.entry来解决了。
Last updated