给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
提示:
1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
Java新特性来解:
class Solution {
public int[] topKFrequent(int[] nums, int k) {
return Arrays.stream(nums)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toList()).subList(0, k)
.stream()
.mapToInt(t -> t.getKey().intValue()).toArray();
}
}
/使用Java 8 Stream API来查找给定数组中出现频率最高的前K个元素。它首先将数组转换为流,然后使用groupingBy收集器将元素分组,并使用counting收集器计算每个元素出现的次数。然后,它使用sorted排序流,并使用subList收集器提取前K个元素,最后使用mapToInt收集器将元素转换为整数数组。/
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/top-k-frequent-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
评论区