Java O(n) Solution Using Java 8 Stream


  • 0
    B
    public class TopKFrequentElements {
        public List<Integer> topKFrequent(int[] nums, int k) {
            List<Integer> list = new ArrayList<>();
            Map<Integer, Long> result = Arrays.stream(nums).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
            result.entrySet().stream().sorted(Map.Entry.<Integer, Long>comparingByValue().reversed()).forEachOrdered(e -> addToList(list,e.getKey(),k));
    
            return list;
        }
    
        public void addToList(List<Integer> list, Integer value, int k) {
            if(list.size()<k) {
                list.add(value);
            }
        }
    
        public static void main(String[] args) {
            new TopKFrequentElements().topKFrequent(new int[] {1,1,1,2,2,3},2).forEach(System.out::println);
        }
    }
    

Log in to reply
 

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