给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
【解题思路】首先对数组进行排序,找到每一个数出现的频率,设置一个大小为k 的数组,如果评率大于该数组内出现频率最小的数,则替换它。
class Solution {
public int[] topKFrequent(int[] nums, int k) {
List<Integer> Nums = Arrays.stream(nums).boxed().collect(Collectors.toList());
Collections.sort(Nums);
int cnt = 0;
int num = 99999;
int[] ans = new int[k];
int[] ansCnt = new int[k];
int min = 0;
for(int i = 0; i < Nums.size(); i++){
if(Nums.get(i) != num){
for(int j = 0; j < k; j++){
if(ansCnt[j] < ansCnt[min])
{
min = j;
}
}
if(num != 99999)
{
if(ansCnt[min] < cnt)
{
ansCnt[min] = cnt;
ans[min] = num;
}
}
num = Nums.get(i);
cnt = 1;
}
else cnt++;
}
for(int j = 0; j < k; j++){
if(ansCnt[j] < ansCnt[min])
{
min = j;
}
}
if(ansCnt[min] < cnt)
{
ansCnt[min] = cnt;
ans[min] = num;
}
return ans;
}
}
int[]数组排序
首先将int[]数组转换为List,再使用Collections.sort()方法对list排序
//方法一:Collections.sort()
int[] nums = {3,0,1,0};
List<Integer> Nums = Arrays.stream(nums).boxed().collect(Collectors.toList());
Collections.sort(Nums);
//方法二:Arrays.sort()
int[] nums = {1,2,3,4}
Arrays.sort(nums);