LeetCode 题解工作台
到目标元素的最小距离
给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数 target 和 start ,请你找出一个下标 i ,满足 nums[i] == target 且 abs(i - start) 最小化 。注意: abs(x) 表示 x 的绝对值。 返回 abs(i - start) 。 题目…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
遍历数组,找到所有等于 的下标,然后计算 $|i - start|$,取最小值即可。 时间复杂度 ,其中 为数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数 target 和 start ,请你找出一个下标 i ,满足 nums[i] == target 且 abs(i - start) 最小化 。注意:abs(x) 表示 x 的绝对值。
返回 abs(i - start) 。
题目数据保证 target 存在于 nums 中。
示例 1:
输入:nums = [1,2,3,4,5], target = 5, start = 3 输出:1 解释:nums[4] = 5 是唯一一个等于 target 的值,所以答案是 abs(4 - 3) = 1 。
示例 2:
输入:nums = [1], target = 1, start = 0 输出:0 解释:nums[0] = 1 是唯一一个等于 target 的值,所以答案是 abs(0 - 0) = 0 。
示例 3:
输入:nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0 输出:0 解释:nums 中的每个值都是 1 ,但 nums[0] 使 abs(i - start) 的结果得以最小化,所以答案是 abs(0 - 0) = 0 。
提示:
1 <= nums.length <= 10001 <= nums[i] <= 1040 <= start < nums.lengthtarget存在于nums中
解题思路
方法一:一次遍历
遍历数组,找到所有等于 的下标,然后计算 ,取最小值即可。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
return min(abs(i - start) for i, x in enumerate(nums) if x == target)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They want you to notice that only indices with nums[i] == target matter, not the values around them.
- question_mark
A strong answer mentions that target is guaranteed to exist, so no fallback case is needed.
- question_mark
If they hint at checking both directions from start, they are steering you toward an outward array search with early stop.
常见陷阱
外企场景- error
Stopping at the first target seen in a left-to-right scan can fail when a later target is closer to start.
- error
Forgetting absolute value leads to wrong comparisons when the target index is left of start.
- error
Overengineering with sorting or extra maps misses that this problem is just a direct array distance check.
进阶变体
外企场景- arrow_right_alt
Return the closest target index instead of the distance, with a clear tie rule if both sides match.
- arrow_right_alt
Remove the guarantee that target exists and return -1 when no matching value appears.
- arrow_right_alt
Process many queries on the same nums, where preprocessing target indices could help repeated lookups.