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
classSolution { 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; } };