Using Priority Queue and HashMap


  • 0
    S
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String, Freq> wordList = new HashMap<String,Freq>();
        List<String> res = new ArrayList<String>();
    
        for(String word : words){
    	    if(wordList.containsKey(word)){
    		    Freq n = wordList.get(word);
    		    n.freq = n.freq+1;
                wordList.put(word,n);
    	    }
    	    else{
    		    Freq f = new Freq(word,1);
    		    wordList.put(word,f);
    	    }
        }
    
    PriorityQueue<Freq> pq = new PriorityQueue<>(k, new Comparator<Freq>(){
    		public int compare(Freq a, Freq b){
    			if(a.freq<b.freq){
    				return 1;
    			}
    			else if (a.freq>b.freq){
    				return -1;
    			}
                else if(a.freq == b.freq){
                    return a.text.toString().compareTo(b.text.toString());
                }
    			else {
    				return 0;
    			}
    		}
    });
    
    for(Map.Entry<String,Freq> mp : wordList.entrySet()){
    	pq.offer(mp.getValue());
    }
    
    while(!pq.isEmpty() && k!=0 ){
    	res.add(pq.poll().text);
        k--;
    }
    
    return res;
    }
    

    }


Log in to reply
 

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