严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Top K Frequent Words 高频题 其它公司也喜欢考

Go down

Top K Frequent Words 高频题 其它公司也喜欢考 Empty Top K Frequent Words 高频题 其它公司也喜欢考

Post by Admin Sat Oct 21, 2017 5:58 pm

class Node{
int freq;
String str;
public Node(String s, int f){
freq = f;
str = s;
}
}

public String[] topKFrequentWords(String[] strs, int k){

if(strs == null || strs.length == 0 || k <= 0){
return null;
}

HashMap<String, Node> map = new HashMap<String, Node>();
for(String str : strs){
if(!map.containsKey(str)){
map.put(str, new Node(str, 1));
}
map.get(str).freq = map.get(str).freq + 1;
}

PriorityQueue<Node> pq = new PriorityQueue<Node>(k, new Comparator<Node>(){
public int compare(Node n1, Node n2){
if(n1.freq == n2.freq){
return n1.str.compareTo(n2.str);
}else{
return n2.freq - n1.freq;
}
}
});

for(String key : map.keySet()){
pq.offer(map.get(key));
}

String[] res = new String[k];
for(int i = 0; i < k; i++){
res[i] = pq.poll().str;
}

return res;
}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum