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:
medium级别,求数组的重复出现的K多的元素。
用map存储数值及对应频率,用优先队列找出前k个,优先队列可以直接存储map的entry、排序(替代了遍历map找最大的过程)。因为优先级队列默认的是小根堆。所以要自定义比较器。
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums={1,1,1,2,2,3};
List list = topKFrequent(nums,2);
System.out.println( JSON.toJSON(list));
}
@SuppressWarnings("unchecked")
public static List topKFrequent(int[] nums, int k) {
List list = new ArrayList();
//coner case
if(nums == null|| nums.length==0){
return list;
}
//遍历
Map map = new HashMap();
for(int i=0; i> pq =
new PriorityQueue<>((a,b)->(b.getValue()-a.getValue() ) );
//保存到queue
for( Map.Entry entry : map.entrySet() ){
pq.add( entry);
}
//输出结果
for (int i = 0; i < k; i++) {
list.add(pq.poll().getKey());
}
return list;
}
Runtime: 42 ms, faster than 48.97% of Java online submissions for Top K Frequent Elements.
Memory Usage: 40.4 MB, less than 68.96% of Java online submissions for Top K Frequent Elements.
有人用可以自动排序的数据结构 TreeMap,也是不用遍历map求最大的。思路是类似的。
看下桶排序,这个之前李教练讲过,没有看过。看下讨论区大神的解法,思路如下:
还是先用map计数,然后建立N+1的桶, 根据map的value存到对应的桶中,桶的编号表示出现的次数,所以取最大的从后往前取。桶排序不是常见的基于比较的排序。
public static List topKFrequent(int[] nums, int k) {
List list = new ArrayList();
//coner case
if(nums == null|| nums.length==0){
return list;
}
//遍历
Map map = new HashMap();
for(int i=0; i[] bucket = new List[nums.length + 1];
// 遍历map,根据value值放到对应的桶中
for( Map.Entry entry : map.entrySet() ){
Integer value = entry.getValue();
if(bucket[value] == null) {
bucket[value] = new ArrayList();
}
bucket[value] .add(entry.getKey() );
}
//从桶的后面倒序输出
for( int j= bucket.length-1;j>0&& list.size()
Runtime: 11 ms, faster than 88.34% of Java online submissions for Top K Frequent Elements.
Memory Usage: 41.2 MB, less than 31.89% of Java online submissions for Top K Frequent Elements.
快多了。
参考:
https://leetcode.com/problems/top-k-frequent-elements/discuss/81635/3-Java-Solution-using-Array-MaxHeap-TreeMap