您的位置:首页 > 其它

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

2017-07-05 11:27 531 查看
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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: