目录
624. 数组列表中的最大距离
题目描述:
给定 m
个数组,每个数组都已经按照升序排好序了。
现在你需要从两个不同的数组中选择两个整数(每个数组选一个)并且计算它们的距离。两个整数 a
和 b
之间的距离定义为它们差的绝对值 |a-b|
。
返回最大距离。
示例 1:
输入:[[1,2,3],[4,5],[1,2,3]] 输出:4 解释: 一种得到答案 4 的方法是从第一个数组或者第三个数组中选择 1,同时从第二个数组中选择 5 。
示例 2:
输入:arrays = [[1],[1]] 输出:0
提示:
m == arrays.length
2 <= m <= 105
1 <= arrays[i].length <= 500
-104 <= arrays[i][j] <= 104
arrays[i]
以 升序 排序。- 所有数组中最多有
105
个整数。
实现代码与解析:
贪心
class Solution {
public int maxDistance(List<List<Integer>> arrays) {
int res = 0;
int ma = -0x3f3f3f3f ;
int mi = 0x3f3f3f3f;
for (List<Integer> list : arrays) {
int a = list.get(0);
int b = list.get(list.size() - 1);
res = Math.max(res, Math.max(ma - a, b - mi));
ma = Math.max(ma, b);
mi = Math.min(mi, a);
}
return res;
}
}
原理思路:
暴力即可,每次取最大和最小,注意先根据当前列表中的最大值b和最小值a与ma,mi取一次res比较,而不是更新ma和mi。因为需要取不取数组中的最大和最小为答案。