carloscn / structstudy

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

leetcode2164: Sort Even and Odd Indices Independently #350

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:

Sort the values at odd indices of nums in non-increasing order. For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order. Sort the values at even indices of nums in non-decreasing order. For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order. Return the array formed after rearranging the values of nums.

Example 1:

Input: nums = [4,1,2,3] Output: [2,3,4,1] Explanation: First, we sort the values present at odd indices (1 and 3) in non-increasing order. So, nums changes from [4,1,2,3] to [4,3,2,1]. Next, we sort the values present at even indices (0 and 2) in non-decreasing order. So, nums changes from [4,1,2,3] to [2,3,4,1]. Thus, the array formed after rearranging the values is [2,3,4,1].

Example 2:

Input: nums = [2,1] Output: [2,1] Explanation: Since there is exactly one odd index and one even index, no rearrangement of values takes place. The resultant array formed is [2,1], which is the same as the initial array.

Constraints:

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

carloscn commented 1 year ago

Analysis

int32_t sort_even_odd(int32_t *nums, size_t nums_size)
{
    int32_t ret = 0;
    int32_t *a_buf = NULL;
    int32_t *b_buf = NULL;

    UTILS_CHECK_PTR(nums);
    UTILS_CHECK_LEN(nums_size);

    a_buf = (int32_t *)malloc(sizeof(int32_t) * (nums_size / 2 + 1));
    UTILS_CHECK_PTR(a_buf);

    b_buf = (int32_t *)malloc(sizeof(int32_t) * (nums_size / 2 + 1));
    UTILS_CHECK_PTR(b_buf);

    for (size_t i = 0; i < nums_size; i ++) {
        if (i % 2 == 0) {
            a_buf[i/2] = nums[i];
        } else {
            b_buf[i/2] = nums[i];
        }
    }

    for (size_t i = 0; i < nums_size/2; i ++) {
        for (size_t j = 0; j < nums_size/2 - i - 1; j ++) {
            if (a_buf[j] > a_buf[j + 1]) {
                utils_swap_int32(a_buf + j, a_buf + j + 1);
            }
            if (b_buf[j] < b_buf[j + 1]) {
                utils_swap_int32(b_buf + j, b_buf + j + 1);
            }
        }
    }

    for (size_t i = 0; i < nums_size / 2; i ++) {
        nums[2 * i] = a_buf[i];
        nums[2 * i + 1] = b_buf[i];
    }

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

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169124 https://github.com/carloscn/structstudy/commit/fb99d929f953ab76dd6aaf535ed5013a8b3d4c41