题目:https://leetcode-cn.com/problems/top-k-frequent-elements/
代码:
class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); //遍历nums记录每个数字出现的次数 for (Integer num : nums) { map.put(num, map.getOrDefault(num, 0) + 1); } //将map的Map.Entry对象使用list存储,并根据value值从大到小排序 List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet()); list.sort((o1, o2) -> o2.getValue() - o1.getValue()); //取出前k个数 int[] top = new int[k]; for (int i = 0; i < k; i++) { top[i] = list.get(i).getKey(); } return top; } }
定义一个map,key为数字,value为数字出现的次数。遍历nums数组计算出map的值,之后根据value的值对map从大到小排序(这里用了lamdba表达式),取出前k个数即可。