LeetCode 题解工作台
下标对中的最大距离
给你两个 非递增 的整数数组 nums1 和 nums2 ,数组下标均 从 0 开始 计数。 下标对 (i, j) 中 0 且 0 。如果该下标对同时满足 i 且 nums1[i] ,则称之为 有效 下标对,该下标对的 距离 为 j - i 。 返回所有 有效 …
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
假设 , 的长度分别为 和 。 遍历数组 ,对于每个数字 ,二分查找 在 范围内的数字,找到最后一个大于等于 的位置 ,计算此位置与 的距离,并更新最大距离值 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你两个 非递增 的整数数组 nums1 和 nums2 ,数组下标均 从 0 开始 计数。
下标对 (i, j) 中 0 <= i < nums1.length 且 0 <= j < nums2.length 。如果该下标对同时满足 i <= j 且 nums1[i] <= nums2[j] ,则称之为 有效 下标对,该下标对的 距离 为 j - i 。
返回所有 有效 下标对 (i, j) 中的 最大距离 。如果不存在有效下标对,返回 0 。
一个数组 arr ,如果每个 1 <= i < arr.length 均有 arr[i-1] >= arr[i] 成立,那么该数组是一个 非递增 数组。
示例 1:
输入:nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5] 输出:2 解释:有效下标对是 (0,0), (2,2), (2,3), (2,4), (3,3), (3,4) 和 (4,4) 。 最大距离是 2 ,对应下标对 (2,4) 。
示例 2:
输入:nums1 = [2,2,2], nums2 = [10,10,1] 输出:1 解释:有效下标对是 (0,0), (0,1) 和 (1,1) 。 最大距离是 1 ,对应下标对 (0,1) 。
示例 3:
输入:nums1 = [30,29,19,5], nums2 = [25,25,25,25,25] 输出:2 解释:有效下标对是 (2,2), (2,3), (2,4), (3,3) 和 (3,4) 。 最大距离是 2 ,对应下标对 (2,4) 。
提示:
1 <= nums1.length <= 1051 <= nums2.length <= 1051 <= nums1[i], nums2[j] <= 105nums1和nums2都是 非递增 数组
解题思路
方法一:二分查找
假设 , 的长度分别为 和 。
遍历数组 ,对于每个数字 ,二分查找 在 范围内的数字,找到最后一个大于等于 的位置 ,计算此位置与 的距离,并更新最大距离值 。
时间复杂度 ,其中 和 分别为 和 的长度。空间复杂度 。
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
ans = 0
nums2 = nums2[::-1]
for i, v in enumerate(nums1):
j = len(nums2) - bisect_left(nums2, v) - 1
ans = max(ans, j - i)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate uses binary search effectively for optimization.
- question_mark
Candidate demonstrates understanding of the relationship between the two arrays.
- question_mark
Candidate can handle edge cases and large inputs.
常见陷阱
外企场景- error
Forgetting to handle edge cases where the arrays are very small.
- error
Not optimizing the search for the valid pair using binary search.
- error
Incorrectly assuming that the maximum valid pair is always at the ends of the arrays.
进阶变体
外企场景- arrow_right_alt
Modify the problem to handle arrays in increasing order instead of non-increasing.
- arrow_right_alt
Consider allowing duplicates in the arrays and adjusting the logic to handle these scenarios.
- arrow_right_alt
Extend the problem to find the maximum distance with different constraints, such as allowing negative numbers or non-sorted arrays.