LeetCode 题解工作台
数组列表中的最大距离
给定 m 个数组,每个数组都已经按照升序排好序了。 现在你需要从两个不同的数组中选择两个整数(每个数组选一个)并且计算它们的距离。两个整数 a 和 b 之间的距离定义为它们差的绝对值 |a-b| 。 返回最大距离。 示例 1: 输入: [[1,2,3],[4,5],[1,2,3]] 输出: 4 解释…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们注意到,最大距离一定是两个数组中的一个最大值和另一个最小值之间的距离。因此,我们可以维护两个变量 和 ,分别表示已经遍历过的数组中的最小值和最大值。初始时 和 分别为第一个数组的第一个元素和最后一个元素。 接下来,我们从第二个数组开始遍历,对于每个数组,我们首先计算当前数组的第一个元素和 之间的距离,以及当前数组的最后一个元素和 之间的距离,然后更新最大距离。同时,我们更新 $\te…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给定 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.length2 <= m <= 1051 <= arrays[i].length <= 500-104 <= arrays[i][j] <= 104arrays[i]以 升序 排序。- 所有数组中最多有
105个整数。
解题思路
方法一:维护最大值和最小值
我们注意到,最大距离一定是两个数组中的一个最大值和另一个最小值之间的距离。因此,我们可以维护两个变量 和 ,分别表示已经遍历过的数组中的最小值和最大值。初始时 和 分别为第一个数组的第一个元素和最后一个元素。
接下来,我们从第二个数组开始遍历,对于每个数组,我们首先计算当前数组的第一个元素和 之间的距离,以及当前数组的最后一个元素和 之间的距离,然后更新最大距离。同时,我们更新 和 。
遍历结束后,即可得到最大距离。
时间复杂度 ,其中 为数组的个数。空间复杂度 。
class Solution:
def maxDistance(self, arrays: List[List[int]]) -> int:
ans = 0
mi, mx = arrays[0][0], arrays[0][-1]
for arr in arrays[1:]:
a, b = abs(arr[0] - mx), abs(arr[-1] - mi)
ans = max(ans, a, b)
mi = min(mi, arr[0])
mx = max(mx, arr[-1])
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Recognizes that sorted arrays mean only boundary values influence the maximum distance.
- question_mark
Uses a running minimum and maximum from previously processed arrays.
- question_mark
Explains why updating extremes after computing distances prevents using the same array twice.
常见陷阱
外企场景- error
Updating the global minimum and maximum before computing distances, which can incorrectly compare values from the same array.
- error
Attempting to compare all internal elements instead of using the sorted boundary property.
- error
Forgetting to check both directions: current max minus global min and global max minus current min.
进阶变体
外企场景- arrow_right_alt
Return the pair of values that produces the maximum distance instead of just the distance.
- arrow_right_alt
Modify the problem so arrays are not sorted, requiring preprocessing to find local minima and maxima.
- arrow_right_alt
Extend the task to select k arrays and maximize the spread among chosen elements.