share my java solution using treemap and map!


  • 0
    T
    class Solution {
        public List<String> topKFrequent(String[] words, int k) {
             Map<String,Integer> map = new HashMap<>();
             for(String str:words){
                 map.put(str,map.getOrDefault(str,0)+1);
             }
            
             TreeMap<Integer,List<String>> treemap = new TreeMap<>();
             for(String key:map.keySet()){
                 int count = map.get(key);
                 if(!treemap.containsKey(count)){
                     treemap.put(count,new ArrayList<>());
                 }
                 treemap.get(count).add(key);
             }
            
             List<String> ans = new ArrayList<>();
             while(ans.size()<k){
                 if(treemap.size()==0){
                     break;
                 }
                 int count = treemap.lastKey();
                 List<String> list = treemap.get(count);
                 treemap.remove(count);
                 Collections.sort(list);
                 ans.addAll(list);
             }
            
             while(ans.size()>k){
                 ans.remove(ans.size()-1);
             }
             return ans;
        } 
    }
    

Log in to reply
 

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