Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

I. Problem description

You are given an array of integers with indices starting at 0 nums and two integers key and k. K neighbor is one of the nums subscript subscript I, and there are at least a subscript j make | I – j | < = K and nums = = [j] key.

Returns all K nearest neighbor subscripts in ascending order as a list.

Subject link: all K nearest neighbor subscripts in an array.

Two, the title requirements

The sample

Input: nums = [3,4,9,1,3,9,5], key = 9, k = 1 output: [1,2,3,4,5,6] description: therefore, nums[2] == key and nums[5] == key. - the subscript 0. 2 | | 0 - > k and | | 0 to 5 > k, so there is no make | 0 - j j | < = k and nums = = [j] key. So 0 is not a K nearest neighbor index. 1-2 - the subscript 1. | | < = k and nums [2] = = key, so 1 is a k neighbor subscript. 2-2 - the subscript 2. | | < = k and nums [2] = = key, so 2 is a k neighbor subscript. - to subscript 3, 2 | | 3 - < = k and nums [2] = = key, so 3 is a k neighbor subscript. 4-5 - the subscript 4. | | < = k and nums [5] = = key, so is a 4 k neighbor subscript. - to subscript 5, 5-5 | | < = k and nums [5] = = key, so 5 is a k neighbor subscript. - to subscript 6, 6-5 | | < = k and nums [5] = = key, so 6 is a k neighbor subscript. Therefore, return [1,2,3,4,5,6] in ascending order.Copy the code

inspection

2. The recommended time is 10~30 minutesCopy the code

Third, problem analysis

This is a difficult problem at the beginning, but after reading the case, it is a common circular judgment. This problem is solved in two steps:

1. Find out j

What is j? If nums[j]==key, insert subscript j into v2 array.

2. To find out the I

I is the nearest neighbor subscript. The first for loop iterates over nums, and the second for loop is the array v2 that stores j.

If abs(i-v2[j])<=k, then I is stored in the array v1.

Development:

Abs stands for absolute value.

Four, coding implementation

class Solution {
public:
    vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {
        int i,j,n=nums.size(a);// Initialize the definition
        vector<int>v1,v2;// Array v1, v2
        for(j=0; j<n; j++)/ / to find j
            if(nums[j]==key)// Is equal to key
                v2.push_back(j);
         for(i=0; i<n; i++)/ / find the I
        {
            for(j=0; j<v2.size(a); j++) {if(abs(i-v2[j])<=k)// Determine the condition
                {
                    v1.push_back(i);
                    break;// Exit as long as there is one satisfaction, without complete traversal}}}returnv1; }};Copy the code

V. Test results