LeetCode 题解工作台

到目标元素的最小距离

给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数 target 和 start ,请你找出一个下标 i ,满足 nums[i] == target 且 abs(i - start) 最小化 。注意: abs(x) 表示 x 的绝对值。 返回 abs(i - start) 。 题目…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

遍历数组,找到所有等于 的下标,然后计算 $|i - start|$,取最小值即可。 时间复杂度 ,其中 为数组 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数 targetstart ,请你找出一个下标 i ,满足 nums[i] == targetabs(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 <= 1000
  • 1 <= nums[i] <= 104
  • 0 <= start < nums.length
  • target 存在于 nums
lightbulb

解题思路

方法一:一次遍历

遍历数组,找到所有等于 targettarget 的下标,然后计算 istart|i - start|,取最小值即可。

时间复杂度 O(n)O(n),其中 nn 为数组 numsnums 的长度。空间复杂度 O(1)O(1)

1
2
3
4
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)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

到目标元素的最小距离题解:数组·driven | LeetCode #1848 简单