2200. Find All K-Distant Indices in an Array

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {
int n = nums.size();
vector<int> ret;
vector<pair<int,int>> target;
for(int i=0;i<n;++i){
if(nums[i]==key)target.push_back(make_pair(key, i));
}
for(int i=0;i<n;++i){
if(nums[i] == key){
ret.push_back(i);
}
else{
for(pair p:target){
if(abs(i-p.second)<=k){
ret.push_back(i);
break;
}
}
}
}
return ret;

}
};

analysis

  • time complexity O(n*mlogm)
  • space complexity O(n)