carloscn / structstudy

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

leetcode2089: Find Target Indices After Sorting Array #336

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given a 0-indexed integer array nums and a target element target.

A target index is an index i such that nums[i] == target.

Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.

Example 1:

Input: nums = [1,2,5,2,3], target = 2 Output: [1,2] Explanation: After sorting, nums is [1,2,2,3,5]. The indices where nums[i] == 2 are 1 and 2.

Example 2:

Input: nums = [1,2,5,2,3], target = 3 Output: [3] Explanation: After sorting, nums is [1,2,2,3,5]. The index where nums[i] == 3 is 3.

Example 3:

Input: nums = [1,2,5,2,3], target = 5 Output: [4] Explanation: After sorting, nums is [1,2,2,3,5]. The index where nums[i] == 5 is 4.

Constraints:

1 <= nums.length <= 100 1 <= nums[i], target <= 100

carloscn commented 1 year ago

Analysis

int32_t target_indices(const int32_t *nums, size_t nums_size, int32_t target,
                       int32_t **out, size_t *olen)
{
    int32_t ret = 0;

    UTILS_CHECK_PTR(nums);
    UTILS_CHECK_PTR(out);
    UTILS_CHECK_PTR(olen);
    UTILS_CHECK_LEN(nums_size);

    *out = (int32_t*) malloc(sizeof(int32_t) * nums_size);
    UTILS_CHECK_PTR(*out);

    memcpy(*out, nums, nums_size * sizeof(int32_t));

    for (size_t i = 0; i < nums_size - 1; i ++) {
        for (size_t j = 0; j < nums_size - i - 1; j ++) {
            if ((*out)[j] > (*out)[j + 1]) {
                utils_swap_int32(&((*out)[j]), &((*out)[j + 1]));
            }
        }
    }

    size_t j = 0;
    for (size_t i = 0; i < nums_size; i ++) {
        if ((*out)[i] == target) {
            (*out)[j] = (int32_t) i;
            j ++;
        }
    }

    *olen = j;

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168735 https://github.com/carloscn/structstudy/commit/de62bfc70dc66b4fece8d32ef3b76c847c52cdbb