Java 1 line solution using Stream


  • 0
    Z
    public static List<Integer> topKFrequent(int[] nums, int k) {
            return IntStream.of(nums).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream().sorted((i, j) -> -(int) (i.getValue() - j.getValue())).limit(k).map(i -> i.getKey()).collect(Collectors.toList());
        }
    

Log in to reply
 

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