找出数组中的所有 K 近邻下标

找出数组中的所有 K 近邻下标

https://leetcode.cn/problems/find-all-k-distant-indices-in-an-array/description/?envType=daily-question&envId=2025-06-24

题目

给你一个下标从 0 开始的整数数组 nums 和两个整数 key 和 k 。K 近邻下标 是 nums 中的一个下标 i ,并满足至少存在一个下标 j 使得 |i - j| <= k 且 nums[j] == key 。
以列表形式返回按 递增顺序 排序的所有 K 近邻下标。

示例 1:
输入:nums = [3,4,9,1,3,9,5], key = 9, k = 1
输出:[1,2,3,4,5,6]
解释:因此,nums[2] == key 且 nums[5] == key。

  • 对下标 0 ,|0 - 2| > k 且 |0 - 5| > k,所以不存在 j 使得 |0 - j| <= k 且 nums[j] == key。所以 0 不是一个 K 近邻下标。
  • 对下标 1 ,|1 - 2| <= k 且 nums[2] == key,所以 1 是一个 K 近邻下标。
  • 对下标 2 ,|2 - 2| <= k 且 nums[2] == key,所以 2 是一个 K 近邻下标。
  • 对下标 3 ,|3 - 2| <= k 且 nums[2] == key,所以 3 是一个 K 近邻下标。
  • 对下标 4 ,|4 - 5| <= k 且 nums[5] == key,所以 4 是一个 K 近邻下标。
  • 对下标 5 ,|5 - 5| <= k 且 nums[5] == key,所以 5 是一个 K 近邻下标。
  • 对下标 6 ,|6 - 5| <= k 且 nums[5] == key,所以 6 是一个 K 近邻下标。
    因此,按递增顺序返回 [1,2,3,4,5,6] 。
    示例 2:
    输入:nums = [2,2,2,2,2], key = 2, k = 2
    输出:[0,1,2,3,4]
    解释:对 nums 的所有下标 i ,总存在某个下标 j 使得 |i - j| <= k 且 nums[j] == key,所以每个下标都是一个 K 近邻下标。
    因此,返回 [0,1,2,3,4] 。
    提示:
    1 <= nums.length <= 1000
    1 <= nums[i] <= 1000
    key 是数组 nums 中的一个整数
    1 <= k <= nums.length

题解

根据题目,我们需要找到以j(值==key)为中心的左右两边的下标。
实现上,找到满足条件的j,另外有一个指针i来遍历记录加入到结果,i是j-k,但是为了避免重复加入结果,所以i要比以前加入到结果的i要大。

class Solution {
    public List<Integer> findKDistantIndices(int[] nums, int key, int k) {
        List<Integer> res=new ArrayList<>();
        int n=nums.length;
        int i=0;
        for(int j=0;i<n&&j<n;j++){
            if(nums[j]==key){
                if(i<j-k){
                    i=j-k;
                }
                for(;i<=j+k&&i<n;i++){
                    res.add(i);
                }
            }
        }

        return res;
    }
}

另外看到自己22年的code记录,i的left是0,上次加入的最后值+1,以及j-k中的最大值,i的right是n-1和j+k中的最小值。
实现上i和j和题目描述的i和j相反。

class Solution {
    public List<Integer> findKDistantIndices(int[] nums, int key, int k) {
        //find the values that is key
        int n=nums.length;
        List<Integer> res=new ArrayList<Integer>(n);
        for(int i=0;i<n;i++){
            if(nums[i]==key){
                int left=Math.max(0,i-k);
                int right=Math.min(n-1,i+k);
                for(int j=Math.max(res.isEmpty()?-1:res.get(res.size()-1)+1,left);j<=right;j++){
                    res.add(j);
                }
            }
        }
        return res;
    }
}
posted @ 2025-06-24 22:04  Fanny123  阅读(243)  评论(0)    收藏  举报