哈希表排序

运用哈希表排序时,所使用的参数是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;
    }
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

henulmh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值