瑞士军刀篇

本文介绍了如何使用比较器对二维数组进行排序,并展示了优先队列在存储对象及Map.Entry条目时的应用场景。此外,还提到了一些简单的数学基础知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、给二维数组排序

按照元素的第一维来排序:

只能给对象添加比较器,无法给基础类型添加比较器,数组也是一种对象。

int[][] trips = new int[m][n];
//二维数组的初始化操作
Arrays.sort(trips, new Comparator<int[]>() {
	@Override
	public int compare(int[] o1, int[] o2) {
		
	return o1[0]-o2[0];
	}
			
});

二、使用优先队列(为存储对象编写比较器)

Queue<int[]> queue = new PriorityQueue<int[]>(new Comparator<int[]>() {

	@Override
	public int compare(int[] o1, int[] o2) {
				
		return o1[0]-o2[0];
	}
			
});

三、使用优先队列(为Map.Entry<>条目编写比较器)

        HashMap<Character,Integer> map = new HashMap<>();     
        //...   
        PriorityQueue pq =  new PriorityQueue(new Comparator<Map.Entry<Character,Integer>>(){
            public int compare(Map.Entry<Character,Integer> o1,Map.Entry<Character,Integer> o2){
                return o2.getValue()-o1.getValue();
            }
        });
        
        pq.addAll(map.entrySet());

四、简单数学基础

  • 看到加法到想到求余
  • 数字N若是奇数,则它的约数必然都是奇数;若为偶数,则它的约数可奇可偶。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值