Top K Frequent Words 高频题 其它公司也喜欢考
严氏北美IT公司面试真题汇总和解答论坛 :: LinkedIn公司面试真题: 注册用户可以看到隐藏题目:2017年下半年上机题,8 9 10三个月的onsite面试真题 :: 数据结构的使用:优先级队列
Page 1 of 1
Top K Frequent Words 高频题 其它公司也喜欢考
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;
}
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;
}
Similar topics
» Top K Frequent Words In DataStream高频题其它公司也喜欢考
» House RobberI 高频题 其它公司也喜欢考
» Reverse Words In A StringI
» Reverse Words In AStringII
» House RobberI 高频题 其它公司也喜欢考
» Reverse Words In A StringI
» Reverse Words In AStringII
严氏北美IT公司面试真题汇总和解答论坛 :: LinkedIn公司面试真题: 注册用户可以看到隐藏题目:2017年下半年上机题,8 9 10三个月的onsite面试真题 :: 数据结构的使用:优先级队列
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|