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:
<int> findKDistantIndices(vector<int>& nums, int key, int k) {
vector<int> ans;
vectorint 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) {
.push_back(j);
ans}
= i+k+1;
prev }
}
return ans;
}
};