624.Maximum Distance in Arrays --找数组中的最大差值

Given m arrays, and each array is sorted in ascending order. Now you can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a-b|. Your task is to find the maximum distance.

Example 1:

Input: 
[[1,2,3],
 [4,5],
 [1,2,3]]
Output: 4
Explanation: 
One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.

这道题是找二维数组中的最大差值,其中所选取的整数a和b要来自不同的子数组,并且子数组中的整数是按升序排好的,所以每个子数组的第一个元素是最小的,最后一个元素是最大的,只需要比较每个子数组中的第一个即可找到最小值,比较每个子数组中的第二个即可找到最大值。但是因为整个二维数组的最大值和最小值可能来自相同的子数组,所以用一个变量res来控制,起初res赋值为0,因为差值的绝对值最小为0,然后求当前子数组中的最大值和之前所有子数组的最小值的差的绝对值,并用res记录,再求当前子数组中的最小值和之前所有子数组中的最值的差的绝对值,用res记录。这样保证了既取得最大值,并且所用的整数来自不同的子数组。代码如下:

int res = 0;
		int min = arrays[0][0];
		int max = arrays[0][arrays[0].length-1];
		for(int i=1;i<arrays.length;i++){
			res = Math.max(res, Math.abs(arrays[i][arrays[i].length-1]-min));
			res = Math.max(res, Math.abs(max-arrays[i][0]));
			
			min = Math.min(min,arrays[i][0]);
			max = Math.max(max, arrays[i][arrays[i].length-1]);
		}
		return res;




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值