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.
Input: nums =[1,1,1,1,1,1,1,1,1,1], target =1, start =0Output: 0Explanation: Every value of nums is1, but nums[0] minimizes abs(i - start), which isabs(0-0)=0.
The key idea is to check every index in the array and find the one where the value equals the target and the distance to the start index is minimized. Since the array is small, a simple scan is efficient.
classSolution {
public:int getMinDistance(vector<int>& nums, int target, int start) {
int ans = nums.size();
for (int i =0; i < nums.size(); ++i) {
if (nums[i] == target) {
int d = abs(i - start);
if (d < ans) ans = d;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
funcgetMinDistance(nums []int, targetint, startint) int {
ans:= len(nums)
fori, v:=rangenums {
ifv==target {
d:=i-startifd < 0 { d = -d }
ifd < ans { ans = d }
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintgetMinDistance(int[] nums, int target, int start) {
int ans = nums.length;
for (int i = 0; i < nums.length; i++) {
if (nums[i]== target) {
int d = Math.abs(i - start);
if (d < ans) ans = d;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
fungetMinDistance(nums: IntArray, target: Int, start: Int): Int {
var ans = nums.size
for (i in nums.indices) {
if (nums[i] == target) {
val d = kotlin.math.abs(i - start)
if (d < ans) ans = d
}
}
return ans
}
}
1
2
3
4
5
6
7
8
defgetMinDistance(nums: list[int], target: int, start: int) -> int:
ans = len(nums)
for i, v in enumerate(nums):
if v == target:
d = abs(i - start)
if d < ans:
ans = d
return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnget_min_distance(nums: Vec<i32>, target: i32, start: i32) -> i32 {
letmut ans = nums.len() asi32;
for (i, &v) in nums.iter().enumerate() {
if v == target {
let d = (i asi32- start).abs();
if d < ans { ans = d; }
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
getMinDistance(nums: number[], target: number, start: number):number {
letans=nums.length;
for (leti=0; i<nums.length; i++) {
if (nums[i] ===target) {
constd= Math.abs(i-start);
if (d<ans) ans=d;
}
}
returnans;
}
}