您的位置:首页 > 其它

LeetCode-624:Maximum Distance in Arrays (多数组找元素最大距离)

2017-10-23 12:55 501 查看

Question

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.


Note:

Each given array will have at least 1 number. There will be at least two non-empty arrays;

The total number of the integers in all the m arrays will be in the range of [2, 10000];

The integers in the m arrays will be in the range of [-10000, 10000].

问题解析:

给定的多个(至少两个,且非空)按升序排序好的数组,从其中任意两个数组中各选择一个元素,计算两个元素的距离,找到最大距离。

Answer

Solution 1:

遍历记录最大值距离和最大值最小值即可。

注意不能选择同一个数组中的最大值和最小值;

因为题目中给出的条件是多个数组均已经拍排好序,所以可以将多个数组视为一个数组,数组中的一个元素由两个值组成:
arrays[i][0]
arrays[i][i.length-1]


遍历过程中需要保存每次计算的最大距离以及最大值和最小值;

注意距离要通过两个元素之交叉计算得出,这样可以避免同一个元素大小值计算的问题。

class Solution {
public int maxDistance(List<List<Integer>> arrays) {
int res = 0;
int min = arrays.get(0).get(0);
int max = arrays.get(0).get(arrays.get(0).size() - 1);
for (int i = 1; i < arrays.size(); i++) {
List<Integer> array = arrays.get(i);
res = Math.max(Math.abs(min - array.get(array.size() - 1)), Math.max(Math.abs(array.get(0) - max), res));
min = Math.min(min, array.get(0));
max = Math.max(max, array.get(array.size() - 1));
}
return res;
}
}


时间复杂度:O(n);空间复杂度:O(1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 算法 Array