## Minimum distance to target element

Michael Amin 2021-05-03 07:02:22
minimum distance target element

## 1. subject

Give you an array of integers nums （ Subscript from 0 Start Count ） And two integers target and start , Please find a subscript i , Satisfy nums[i] == target And `abs(i - start) To minimize the ` . Be careful ：abs(x) Express x The absolute value of .

return abs(i - start) .

Topic data assurance target Exist in nums in .

`````` Example 1：
Input ：nums = [1,2,3,4,5], target = 5, start = 3
Output ：1
explain ：nums[4] = 5 Is the only one equal to target Value , So the answer is abs(4 - 3) = 1 .
Example 2：
Input ：nums = [1], target = 1, start = 0
Output ：0
explain ：nums[0] = 1 Is the only one equal to target Value , So the answer is abs(0 - 0) = 1 .
Example 3：
Input ：nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
Output ：0
explain ：nums Every value in is 1 ,
but nums[0] send abs(i - start) The results are minimized , So the answer is abs(0 - 0) = 0 .
Tips ：
1 <= nums.length <= 1000
1 <= nums[i] <= 10^4
0 <= start < nums.length
target Exist in nums in
``````

source ： Power button （LeetCode）

## 2. Problem solving

• Imitate according to the meaning of the topic
``````class Solution {

public:
int getMinDistance(vector<int>& nums, int target, int start) {

int ans = INT_MAX;
for(int i = 0; i < nums.size(); i++)
{

if(nums[i] == target && ans > abs(i-start))
{

ans = abs(i-start);
}
}
return ans;
}
};
``````

4 ms 9.3 MB C++

Long click or sweep code pay attention to my official account （Michael amin ）, Come on together 、 Learn together ！

https://qdmana.com/2021/05/20210503070136668O.html