[LeetCode] Find All K-Distant Indices in an Array

2200. Find All K-Distant Indices in an Array

You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key.

Return a list of all k-distant indices sorted in increasing order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] == key) {
int st = max(i - k, res.empty() ? 0 : res.back() + 1);
int ed = min((int)nums.size() - 1, i + k);
for(int j = st; j <= ed; j++) {
res.push_back(j);
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/13/PS/LeetCode/find-all-k-distant-indices-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.