my 12 lines java solution


  • 0
    J
    public List<Integer> topKFrequent(int[] nums, int k) {
        Map<Integer, Long> map = Arrays.stream(nums)
                .boxed()  
                .collect(Collectors.groupingBy(p->p,Collectors.counting()));
        List<Map.Entry<Integer,Long>> entryList = new ArrayList(map.entrySet());
        List<Integer> list = entryList.stream()
                .sorted((p,q) -> (q.getValue().intValue() - p.getValue().intValue()))
               .limit(k)
                .map(p -> p.getKey())
                .collect(Collectors.toList());
        return list;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.