问题描述
给你一个整数数组 nums 和一个整数 k,请你用一个字符串返回其中出现频率前 k 高的元素。请按升序排列。
你所设计算法的时间复杂度必须优于 O(n log n),其中 n 是数组大小。
输入
- nums: 一个正整数数组
- k: 一个整数
- 返回一个包含 k 个元素的字符串,数字元素之间用逗号分隔。数字元素按升序排列,表示出现频率最高的 k 个元素。
参数限制
- 1 <= nums[i] <= 10^4
- 1 <= nums.length <= 10^5
- k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
测试样例
样例1:
输入:nums = [1, 1, 1, 2, 2, 3], k = 2
输出:"1,2"
解释:元素 1 出现了 3 次,元素 2 出现了 2 次,元素 3 出现了 1 次。因此前两个高频元素是 1 和 2。
样例2:
输入:nums = [1], k = 1
输出:"1"
样例3:
输入:nums = [4, 4, 4, 2, 2, 2, 3, 3, 1], k = 2
输出:"2,4"
解题思路
使用map用来计算频率,使用优先队列获取前k个高频的值,最后利用列表排序后返回
Java代码
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static String solution(int[] nums, int k) {
// Please write your code here
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> map.get(o2) - map.get(o1));
queue.addAll(map.keySet());
List<Integer> list = new ArrayList<>();
for (int i = 0; i < k; i++) {
list.add(queue.poll());
}
Collections.sort(list);
return list.stream().map(String::valueOf).collect(Collectors.joining(","));
}
public static void main(String[] args) {
// You can add more test cases here
int[] nums1 = { 1, 1, 1, 2, 2, 3 };
int[] nums2 = { 1 };
System.out.println(solution(nums1, 2).equals("1,2"));
System.out.println(solution(nums2, 1).equals("1"));
}
}