Accepted One liner Java 8 :)


  • 2
    public static List<Integer> topKFrequent(int[] nums, int k) {
            return Arrays.stream(nums).boxed().collect(Collectors.groupingBy(Function.identity(), 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) {
            return Arrays.stream(nums)
                    .boxed()
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                    .entrySet().stream()
                    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                    .limit(k)
                    .map(e -> e.getKey())
                    .collect(Collectors.toList());
        }
    

Log in to reply
 

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