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 <= 10^5
1 <= arrays[i].length <= 500
-10^4 <= arrays[i][j] <= 10^4
arrays[i]
以 升序 排序。- 所有数组中最多有
10^5
个整数。
题解¶
统计出所有数组中最大的最大值和次大的最大值,以及最小的最小值和次小的最小值,以及它们所在的数组。
- 当最大的最大值和最小的最小值出现且仅出现在同一个数组里时,此时不能选择这两个数作差得到结果。需要使用最大的最大值和次小的最小值之差,或者次大的最大值和最小的最小值之差作为结果(取两者中更大的)。
- 其余情况可以直接取最大的最大值和最小的最小值之差。
class Solution:
def maxDistance(self, arrays: List[List[int]]) -> int:
ub = 100001
top1, top1Index, top2, top2Index = -ub, [], -ub, []
bot1, bot1Index, bot2, bot2Index = ub, [], ub, []
for i, arr in enumerate(arrays):
if arr[-1] > top1:
top2 = top1
top2Index = top1Index
top1 = arr[-1]
top1Index = [i]
elif arr[-1] == top1:
top1Index.append(i)
elif arr[-1] > top2:
top2 = arr[-1]
top2Index = [i]
elif arr[-1] == top2:
top2Index.append(i)
if arr[0] < bot1:
bot2 = bot1
bot2Index = bot1Index
bot1 = arr[0]
bot1Index = [i]
elif arr[0] == bot1:
bot1Index.append(i)
elif arr[0] < bot2:
bot2 = arr[0]
bot2Index = [i]
elif arr[0] == bot2:
bot2Index.append(i)
if len(bot1Index) == 1 and len(top1Index) == 1 \
and bot1Index[0] == top1Index[0]:
return max(top1 - bot2, top2 - bot1)
else:
return top1 - bot1