2200: Find-All-K-Distant-Indices-in-an-Array
Easy
table of contents
We first initialize an ans array to keep track of
all our answer indices.
Basically just iterate through the array nums, checking
at each index to see if nums[i] == key:
code
class Solution {
public:
vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {
vector<int> ans;
int prev = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == key) {
for (int j = max(prev, i-k); j < min((int)nums.size(), i+k+1); ++j) {
ans.push_back(j);
}
prev = i+k+1;
}
}
return ans;
}
};