阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给你一个整数数组 nums(下标从 0 开始)以及两个整数 target 和 start,找出一个下标 i,满足 nums[i] == target 且 abs(i - start) 最小。 返回最小的绝对值。题目保证 target 一定存在于数组中。
示例:
输入:nums = [1,2,3,4,5], target = 5, start = 3 输出:1 解释:nums[4] = 5,abs(4-3)=1。
package com.sheeta1998.lec.lc1848;
class lc3600_lc3699.lc3660.Solution {
public int getMinDistance(int[] nums, int target, int start) {
int ans = 999999999;
for (int i = start; i < nums.length; i++) {
if (nums[i] == target) {
ans = Math.min(ans, Math.abs(start - i));
}
}
for (int i = start; i >= 0; i--) {
if (nums[i] == target) {
ans = Math.min(ans, Math.abs(start - i));
}
}
return ans;
}
}从 start 向左右同步扩展查找,找到第一个 target 就直接返回,不用遍历全数组:
class lc3600_lc3699.lc3660.Solution {
public int getMinDistance(int[] nums, int target, int start) {
int n = nums.length;
int d = 0;
while (true) {
int left = start - d;
int right = start + d;
if (left >= 0 && nums[left] == target) return d;
if (right < n && nums[right] == target) return d;
d++;
}
}
}时间复杂度:
空间复杂度: