Solution with elements of Java8


  • 0
    A

    Unfortunately iteration via queue doesn't maintain priority queue invariant, otherwise solution would be fully declarative:

    PriorityQueue<Map.Entry<Integer, Long>> q =
    new PriorityQueue<>((o1, o2) -> Long.compare(o2.getValue(), o1.getValue()));

    q.addAll(Arrays.stream(nums)
            .boxed()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet());
    
    List<Integer> result = new ArrayList<>();
    while (k>0) {
        result.add(q.remove().getKey());
        k--;
    }
    return result;

Log in to reply
 

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