724. Neighbours within k distance

Given an integer array nums with n values and a value k, return an array containing the number of neighbours for each element of the array.

An element x is the neighbour of element y if x falls in the range [y-k, y+k] (inclusive).

Example 1:

Input: nums = [1, 4, 7, 8, 9], k = 3

Output: [2, 3, 4, 3, 3]

Explanation: Neighbours of 1 = [1, 4]

Neighbours of 4 = [1, 4, 7]

Neighbours of 7 = [4, 7, 8, 9]

Neighbours of 8 = [7, 8, 9]

Neighbours of 9 = [7, 8, 9]

Example 2:

Input: nums = [10, 3, 6, 9, 4], k = 4

Output: [3, 3, 5, 3, 3]

Explanation: Neighbours of 10 = [6, 9, 10]

Neighbours of 3 = [3, 4, 6]

Neighbours of 6 = [3, 4, 6, 9, 10]

Neighbours of 9 = [6, 9, 10]

Neighbours of 4 = [3, 4, 6]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • n == Number of elements in nums
  • 1 <= n <= 105
  • -1000 <= nums[i] <= 1000
  • 0 <= k <= 104
0
class Solution {
public:
vector<int> neighboursWithKDistance(vector<int>& nums, int k) {
 
}
};
Test Case

Input:

K
Nums