Accepted One liner Java 8 :)

  • 2
    public static List<Integer> topKFrequent(int[] nums, int k) {
            return, Collectors.counting()))
                    .entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).limit(k).map(e -> e.getKey()).collect(Collectors.toList());

    A more split down version of the code:

    public static List<Integer> topKFrequent1(int[] nums, int k) {
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                    .map(e -> e.getKey())

Log in to reply

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