给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
代码
class Solution {public int[] topKFrequent(int[] nums, int k) {Map<Integer,Integer>map=new HashMap<>();for(int c:nums) map.put(c,map.getOrDefault(c,0)+1);//用map存储数字及其出现的次数int[][] temp=new int[map.keySet().size()][2];int i=0;for(int c:map.keySet())//转变为二维数组{temp[i][0]=c;temp[i][1]=map.get(c);i++;}Arrays.sort(temp,(o1, o2) -> o2[1]-o1[1]);//排序int[] h=new int[k];for(i=0;i<k;i++) h[i]=temp[i][0];//截取结果return h;}
}