运用哈希表排序时,所使用的参数是Map.Entry<key,value>
Map.Entry是Map接口中的一个内部接口,这个接口的对象中包含了K和V;
获取K的方式是Map.Entry对象名.getKey(),获取V的方式是Map.Entry对象名.getValue();
// 先按照value升序 再按照key降序的排序规则
class px implements Comparator<Map.Entry<String,Integer>>{
public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b){
if(a.getValue()==b.getValue())
return b.getKey().compareTo(a.getKey());
return a.getValue()-b.getValue();
}
}
主要针对的题型是,给出一组数据,取前K个…最大或最小
运用 优先队列 + 哈希表排序
优先队列中存储<key,value>键值对。
例题:
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
代码:
class px implements Comparator<Map.Entry<String,Integer>>{
public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b){
if(a.getValue()==b.getValue())
return b.getKey().compareTo(a.getKey());
return a.getValue()-b.getValue();
}
}
class Solution {
public List<String> topKFrequent(String[] words, int k) {
HashMap<String, Integer> m = new HashMap<String, Integer>();
for(String i:words)
{
m.put(i, m.getOrDefault(i, 0)+1); // getOrDefault 如果key存在的话则取此key对应的value值,不存在的话取0
}
PriorityQueue<Map.Entry<String, Integer>> p = new PriorityQueue<Map.Entry<String,Integer>>(new px()); // 按照此排序规则构建从上往下 value依次增大,value相同则key依次减小
for(Map.Entry<String, Integer> entry : m.entrySet()) // entrySet(),所有<key,value>对
{
p.offer(entry);
if(p.size()>k)
p.poll();
}
List<String> ret = new ArrayList<String>();
while (!p.isEmpty()) {
ret.add(p.poll().getKey()); // 上述那么建堆的目的就是这时从堆顶一个个出来时是按照value递减、value相同则key递增,存进ret中。
}
Collections.reverse(ret);
return ret;
}
}