题目
给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数 target 和 start ,请你找出一个下标 i ,满足 nums[i] == target 且 abs(i - start) 最小化 。注意:abs(x) 表示 x 的绝对值。
返回 abs(i - start) 。
题目数据保证 target 存在于 nums 中。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-distance-to-the-target-element
O(n^2)解法
class Solution {
public int getMinDistance(int[] nums, int target, int start) {
int min = 0;
int len = nums.length;
int minDistance = nums.length;
// 循环,找出数组中等于target的下标
for(int i=0;i<len;i++){
if(nums[i] == target){
// 计算当前i和start的绝对值
int distance = Math.abs(i - start);
if(distance < minDistance){
minDistance = distance;
}
min = i;
}
}
return minDistance;
}
}
该博客介绍了一种解决LeetCode上找到数组中目标值与指定下标间最小距离问题的O(n^2)方法。代码实现了一个名为getMinDistance的函数,遍历数组找出等于目标值的元素,并计算与起始下标的绝对值,从而找到最小距离。

592

被折叠的 条评论
为什么被折叠?



