Leetcode每日一题 —— 1848. 到目标元素的最小距离

2026-04-13 12:081阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐
问题描述:
力扣 LeetCode

1848. 到目标元素的最小距离 - 力扣(LeetCode)

1848. 到目标元素的最小距离 - 给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数 target 和 start ,请你找出一个下标 i ,满足 nums[i] == target 且 abs(i - start) 最小化 。注意:abs(x) 表示 x 的绝对值。 返回 abs(i - start) 。 题目数据保证 target 存在于 nums 中。 示例 1: 输入:nums = [1,2,3,4,5], target = 5, start =...

思路
直接按题目思路来即可。遍历数组找到target,计算并更新距离是否最小。

代码

class Solution { public int getMinDistance(int[] nums, int target, int start) { int ans = Integer.MAX_VALUE; for (int i = 0; i < nums.length; i++){ if (nums[i] == target) { ans = Math.min(ans, Math.abs(i - start)); } } return ans; } } 网友解答:


--【壹】--:

这就是我该做的题.jpg

题目已经把思路给出来了。

class Solution { public: int getMinDistance(vector<int>& nums, int target, int start) { int minAbs=nums.size(); for(int i=0;i<nums.size();i++){ if(nums[i]==target){ minAbs=min(minAbs,abs(i-start)); } } return minAbs; } };

今天要去面试了,就不复习其他力扣题了,要八股抱佛脚了


--【贰】--:

每日看题学习咯,跟着大佬每天学习一下,慢慢来吧


--【叁】--:

hard写不出来,easy没营养,感觉报废了。

class Solution { public: int getMinDistance(vector<int>& nums, int target, int start) { int n = nums.size(); int res = n; for(int i = 0; i < n; i++) { if(nums[i] == target) { res = min(res,abs(i - start)); } } return res; } };