Accepted Java Solution using HashMap and TreeMap with custom Comparator


  • 0
    G
    class ValueComparator implements Comparator<Integer> {
        Map map;
        public ValueComparator(Map map) {
            this.map = map;
        }
        public int compare(Integer a, Integer b) {
            if((Integer)map.get(a) >= (Integer)map.get(b)) {
                return -1;
            } else {
                return 1;
            }
        }
    }
    
    public class Solution {
        
        public List<Integer> topKFrequent(int[] nums, int k) {
            Map<Integer,Integer> hm = new TreeMap<>();
            int val;
            for(int num : nums){
                val = 0;
                if(hm.containsKey(num)){
                    val = hm.get(num);
                }
                hm.put(num,++val);
            }
    
            TreeMap<Integer,Integer> tm = new TreeMap<>(new ValueComparator(hm));
            tm.putAll(hm);//when getting added, they will get ordered based on ValueComparator implementation
    
            int counter = 0;
            List<Integer> ls = new ArrayList<>();
            for(Integer key : tm.keySet()){
                ls.add(key);
                counter++;
                if(counter==k) break;
            }
            return ls;
        }
    }

Log in to reply
 

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