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:
- if
true, then we can reiterate through surrounding elements and add them to theansarray.
- to avoid adding duplicate elements, we keep track of the maximum element added to the
ansarray and ensure that all future elements have a greater index- if
false, then we just continue.
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;
}
};
complexity
- Time:
O(n)wherenis the size ofnums- Space:
O(1)
time taken
- 9 minutes and 52 seconds