欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

TOP K frequent-elements

程序员文章站 2022-07-14 22:49:19
...

TOP K frequent-elements

class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        List<Integer> list = new LinkedList<>();
        Queue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(k, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer,Integer> e1, Map.Entry<Integer,Integer> e2) {
                
                return e1.getValue() - e2.getValue();
            }
        });
        Map<Integer, Integer> map = new HashMap<>();
        for (int n: nums) {
            map.put(n, map.containsKey(n) ? map.get(n) + 1 : 1);
        }
        for (Map.Entry<Integer, Integer> e: map.entrySet()) {
            if (queue.size() < k) {
                queue.add(e);
            } else if (e.getValue() > queue.peek().getValue()){
                queue.poll();
                queue.add(e);
            }
        }
        while (queue.size() > 0) {
            list.add(queue.poll().getKey());
        }
    
        return list;
    }
}

 

class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        List<Integer> list = new LinkedList<>();
        int count = 0;
        Map<Integer, Integer> map = new HashMap<>();
        Map<Integer, Set<Integer>> table = new HashMap<>();
        for (int n: nums) {
            map.put(n, map.containsKey(n) ? map.get(n) + 1 : 1);
        }
        for (Map.Entry<Integer, Integer> e : map.entrySet()) {
            int val = e.getValue();
            int key = e.getKey();
            if (table.containsKey(val)) {
                Set<Integer> set = table.get(val);
                set.add(key);
                table.put(val, set);
            } else {
                Set<Integer> set = new HashSet<>();
                set.add(key);
                table.put(val, set);
            }
            if (val >= count) count = val;
        }
        while  (list.size() < k) {
            if (table.containsKey(count)) {
                Set<Integer> set = table.get(count);
                for (int n : set) {
                    if (list.size() < k) {
                        list.add(n);
                    } else return list;
                }
            } 
            count--;
            
        }
        
    
        return list;
    }
}