carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2200: Find All K-Distant Indices in an Array #357

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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.

Example 1:

Input: nums = [3,4,9,1,3,9,5], key = 9, k = 1 Output: [1,2,3,4,5,6] Explanation: Here, nums[2] == key and nums[5] == key.

Example 2:

Input: nums = [2,2,2,2,2], key = 2, k = 2 Output: [0,1,2,3,4] Explanation: For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index. Hence, we return [0,1,2,3,4].

Constraints:

1 <= nums.length <= 1000 1 <= nums[i] <= 1000 key is an integer from the array nums. 1 <= k <= nums.length

carloscn commented 1 year ago

Analysis

int32_t find_k_distant_indices(int32_t *nums, size_t nums_size, int32_t key, int32_t k, size_t *return_size)
{
    int32_t ret = 0;
    int32_t *buffer = NULL;

    UTILS_CHECK_PTR(nums);
    UTILS_CHECK_PTR(return_size);
    UTILS_CHECK_LEN(nums_size);

    buffer = (int32_t *)calloc(sizeof(int32_t), nums_size);
    UTILS_CHECK_PTR(buffer);

    int32_t buffer_sz = 0;
    for (size_t i = 0; i < nums_size; i ++) {
        if (nums[i] == key) {
            buffer[buffer_sz] = i;
            buffer_sz ++;
        }
    }

    int32_t m = 0;
    for (int32_t i = 0; i < nums_size; i ++) {
        for (int32_t j = 0; j < buffer_sz; j ++) {
            if (utils_int32_abs(i - buffer[j]) <= k) {
                nums[m ++] = i;
                break;
            }
        }
    }

    *return_size = (size_t) m;

finish:
    UTILS_SAFE_FREE(buffer);
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169817 https://github.com/carloscn/structstudy/commit/872e1b7db474d301fcccd47fd820e9ba9654ca20