#1848

Minimum Distance to the Target Element

pupil · 430 · lc easy +25 · verified · 54.2% accepted · 391 likes · top 46%

Description

Given a 0-indexed integer array nums, an integer target, and an integer start, find the minimum value of abs(i - start) for any index i where nums[i] == target.

Return that minimum distance. It is guaranteed target exists in nums.

Example 1:

Input: nums = [1,2,3,4,5], target = 5, start = 3
Output: 1
Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.

Example 2:

Input: nums = [1], target = 1, start = 0
Output: 0
Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.

Example 3:

Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
Output: 0
Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.

Code

1
2
3