您的位置:首页 > 其它

LeetCode解题思路之Maximum Distance in Arrays

2017-06-21 00:00 337 查看
##问题描述
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.

题意是给定一个数组1,数组1中的元素是数组2,数组1和2的元素个数范围为[2,10000],数组2中元素是有序排列的整数,数值范围在[-10000,10000]。

然后我们从每个数组中取一个值,与其他数组中的值做差值计算,结果计算出最大的差值。

有一个地方要注意一下,同一个数组2中的最大差值不计入结果中。

##解题思路

因为数组2是有序的,那么计算差值的时候只要取最小值和最大值参与计算即可,其他的值不用考虑

缓存所有元素中最大值和最小值minValue,maxValue,每次与当前数组2中的边界元素做交叉计算,最大的差值计入到结果中

##代码

int maxDistance(int** arrays, int arraysRowSize, int *arraysColSizes)
{
int minValue = 10000;
int maxValue = -10000;
int retValue = -20000;
for (int row = 0; row < arraysRowSize; row++)
{
int minCol = 0;
int maxCol = arraysColSizes[row];
int curMinValue = arrays[row][minCol];
int curMaxValue = arrays[row][maxCol-1];

if (0 != row)
{
//交叉计算,保存最大差值
int value1 = curMaxValue - minValue;
int value2 = maxValue - curMinValue;
int maxDifValue = value1>value2?value1:value2;
if (maxDifValue > retValue)
{
retValue = maxDifValue;
}
}

if (minValue > curMinValue)
{
minValue = curMinValue;
}
if (maxValue < curMaxValue)
{
maxValue = curMaxValue;
}
}

return retValue;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode