Appearance
0347-前K个高频元素
https://leetcode.cn/problems/top-k-frequent-elements
给你一个整数数组 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 个高频元素的集合是唯一的
进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。
思路
将数组排序加入字典表,字典表储存个数,记录最大个数
参考代码
csharp
public class Solution {
public int[] TopKFrequent(int[] nums, int k) {
//统计次数
Dictionary<int,int> dict = new Dictionary<int,int>();
for(int i=0 ; i<nums.Length; i++){
if(!dict.ContainsKey(nums[i])){
dict.Add(nums[i],1);
}
else{
dict[nums[i]]++;
}
}
//输出到二维数组
int[][] arr = new int[dict.Count][];
int index = 0;
foreach(int key in dict.Keys){
arr[index] = new int[2];
arr[index][0] = key;
arr[index][1] = dict[key];
index++;
}
//按照次数降序
Array.Sort(arr,(a, b)=>{
if(a[1] < b[1]){
return 1;
}
if(a[1] > b[1]){
return -1;
}
return 0;
});
int[] result = new int[k];
for(int i=0; i<k; i++){
result[i] = arr[i][0];
}
return result;
}
}
AlgoPress