Leetcode 1848. Minimum Distance to the Target Element
You are given an integer array nums
(0-indexed) and two integers target
and start
. The array contains positive integers only. Your task is to find the minimum distance between the start
index and any index i
such that nums[i] == target
.
The distance between two indices i
and j
is abs(i - j)
(the absolute difference).
Input: nums = [1,2,3,4,5], target = 5, start = 3
Output: 1
Explanation: The target is at index 4. The distance between 3 and 4 is 1.
start
be out of bounds?
start
is always a valid index within nums
.target
is not present in the array?
We iterate through the array, checking each element. If the element matches the target, we calculate the distance from the start
index and keep track of the minimum distance encountered. This ensures we only go through the array once, achieving an efficient solution.
#include <vector>
#include <cmath>
#include <algorithm>
#include <climits>
int getMinDistance(std::vector<int>& nums, int target, int start) {
int minDistance = INT_MAX; // Use a large number to initialize minimum distance
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == target) {
minDistance = std::min(minDistance, std::abs(i - start));
}
}
return minDistance;
}
n
is the number of elements in the array nums
. We need to iterate through the entire array in the worst case.This approach ensures that we efficiently find the minimum distance to the target element in a single pass through the array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?