LeetCode 题解工作台
限制条件下元素之间的最小绝对差
给你一个下标从 0 开始的整数数组 nums 和一个整数 x 。 请你找到数组中下标距离至少为 x 的两个元素的 差值绝对值 的 最小值 。 换言之,请你找到两个下标 i 和 j ,满足 abs(i - j) >= x 且 abs(nums[i] - nums[j]) 的值最小。 请你返回一个整数,…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们创建一个有序集合,用于存储距离当前下标至少为 的元素。 接下来,我们从下标 $i = x$ 开始枚举,每次将 $nums[i - x]$ 加入到有序集合中。然后找出有序集合中与 最接近的两个元素,它们的差值绝对值的最小值就是答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 和一个整数 x 。
请你找到数组中下标距离至少为 x 的两个元素的 差值绝对值 的 最小值 。
换言之,请你找到两个下标 i 和 j ,满足 abs(i - j) >= x 且 abs(nums[i] - nums[j]) 的值最小。
请你返回一个整数,表示下标距离至少为 x 的两个元素之间的差值绝对值的 最小值 。
示例 1:
输入:nums = [4,3,2,4], x = 2 输出:0 解释:我们选择 nums[0] = 4 和 nums[3] = 4 。 它们下标距离满足至少为 2 ,差值绝对值为最小值 0 。 0 是最优解。
示例 2:
输入:nums = [5,3,2,10,15], x = 1 输出:1 解释:我们选择 nums[1] = 3 和 nums[2] = 2 。 它们下标距离满足至少为 1 ,差值绝对值为最小值 1 。 1 是最优解。
示例 3:
输入:nums = [1,2,3,4], x = 3 输出:3 解释:我们选择 nums[0] = 1 和 nums[3] = 4 。 它们下标距离满足至少为 3 ,差值绝对值为最小值 3 。 3 是最优解。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 1090 <= x < nums.length
解题思路
方法一:有序集合
我们创建一个有序集合,用于存储距离当前下标至少为 的元素。
接下来,我们从下标 开始枚举,每次将 加入到有序集合中。然后找出有序集合中与 最接近的两个元素,它们的差值绝对值的最小值就是答案。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def minAbsoluteDifference(self, nums: List[int], x: int) -> int:
sl = SortedList()
ans = inf
for i in range(x, len(nums)):
sl.add(nums[i - x])
j = bisect_left(sl, nums[i])
if j < len(sl):
ans = min(ans, sl[j] - nums[i])
if j:
ans = min(ans, nums[i] - sl[j - 1])
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Evaluate the candidate's understanding of binary search and its application to constrained problems.
- question_mark
Look for clarity in the explanation of how to handle the index separation constraint efficiently.
- question_mark
Check for familiarity with ordered set or tree-based data structures for optimizing search operations.
常见陷阱
外企场景- error
Failing to efficiently manage the index separation constraint and checking all pairs directly can lead to time-limit exceeded errors.
- error
Overlooking the impact of large input sizes and failing to optimize the solution with binary search or an ordered set.
- error
Confusing the problem with simpler pair difference problems that do not have the index separation requirement.
进阶变体
外企场景- arrow_right_alt
Adjusting the index separation constraint (e.g., making it larger) can change the approach and affect performance.
- arrow_right_alt
Solving the problem for an array with a fixed length or pre-sorted array may require different optimizations.
- arrow_right_alt
Extending the problem to multidimensional arrays or higher-dimensional constraints would introduce added complexity.