【题目描述】
给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
https://leetcode.cn/problems/top-k-frequent-elements/?favorite=2cktkvj
对比:【LeeCode】215. 数组中的第K个最大元素
【LeeCode】692. 前K个高频单词
【示例】
【代码】admin
map.entrySet().sorted(Collections.reverseOrder(Map.Entry.comparingByValue))).map(x -> x.getKey()).limit()
package com.company;
import java.util.*;
import java.util.stream.Collectors;
// 2022-02-08
class Solution {
public int[] topKFrequent(int[] nums, int k) {
int[] res = new int[k];
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
List<Integer> collect = map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).map(x -> x.getKey()).limit(k).collect(Collectors.toList());
System.out.println(collect);
for (int i = 0; i < k; i++){
res[i] = collect.get(i);
}
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().topKFrequent( new int[]{1,1,1,2,2,3}, 2); // 输出: [1,2]
new Solution().topKFrequent(new int[]{1}, 1); // 输出: [1]
}
}
【代码】代码随想录
基于队列来排序
class Solution {
public int[] topKFrequent(int[] nums, int k) {
int[] result = new int[k];
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
// 根据map的value值,构建于一个大顶堆(o1 - o2: 小顶堆, o2 - o1 : 大顶堆)
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
for (Map.Entry<Integer, Integer> entry : entries) {
// [1=3, 2=2, 3=1]
queue.offer(entry);
}
for (int i = k - 1; i >= 0; i--) {
result[i] = queue.poll().getKey();
}
return result;
}
}
public class Test {
public static void main(String[] args) {
new Solution().topKFrequent( new int[]{1,1,1,2,2,3}, 2); // 输出: [1,2]
new Solution().topKFrequent(new int[]{1}, 1); // 输出: [1]
}
}