对Map中的Value进行排序,并且只取Map中的key作为返回
作者:互联网
class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer,Integer> map = new HashMap<>(); int[] res = new int[k]; for(int num:nums){ map.put(num,map.getOrDefault(num,0)+1); } List<Integer> list = map.entrySet().stream().sorted((a,b) ->b.getValue() - a.getValue()).map(a->a.getKey()).collect(Collectors.toList()); List<Integer> list1 = list.subList(0,k); for(int i =0;i<k;i++){ res[i] = list1.get(i); } return res; } } 力扣347
标签:Map,map,int,只取,nums,Value,num,new 来源: https://www.cnblogs.com/baotianyi/p/16351017.html