[LeetCode] Minimum Distance to the Target Element

1848. Minimum Distance to the Target Element

Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.

Return abs(i - start).

It is guaranteed that target exists in nums.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int getMinDistance(vector<int>& nums, int target, int start) {
int res = INT_MAX;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] == target) res = min(res, abs(i - start));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/02/PS/LeetCode/minimum-distance-to-the-target-element/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.