carloscn / structstudy

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

leetcode2341: Maximum Number of Pairs in Array #384

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

You are given a 0-indexed integer array nums. In one operation, you may do the following:

Choose two integers in nums that are equal. Remove both integers from nums, forming a pair. The operation is done on nums as many times as possible.

Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible.

Example 1:

Input: nums = [1,3,2,1,3,2,2] Output: [3,1] Explanation: Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2]. Form a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2]. Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2]. No more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.

Example 2:

Input: nums = [1,1] Output: [1,0] Explanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = []. No more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums. Example 3:

Input: nums = [0] Output: [0,1] Explanation: No pairs can be formed, and there is 1 number leftover in nums.

Constraints:

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

carloscn commented 11 months ago

Analysis

static int32_t number_of_pairs(int32_t *nums, size_t nums_size, int32_t *out, size_t *o_len)
{
    int32_t ret = 0;
    STACK_T *stack = NULL;

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

    stack = stack_malloc(STACK_DEFAULT_SIZE);
    UTILS_CHECK_PTR(stack);

    ret = utils_sort_int32_array(nums, nums_size, ORDER_BY_ASCEND);
    UTILS_CHECK_RET(ret);

    for (size_t i = 0; i < nums_size; i ++) {
        if (stack_get_top(stack) == 0) {
            ret = stack_push(stack, nums[i]);
            UTILS_CHECK_RET(ret);
            continue;
        }
        int64_t e = 0;
        ret = stack_peek(stack, &e);
        UTILS_CHECK_RET(ret);

        ret = ((int32_t)e == nums[i]) ?
              stack_pop(stack, NULL):
              stack_push(stack, nums[i]);
        UTILS_CHECK_RET(ret);
    }

    *o_len = 0;
    size_t deleted_pair_len = (nums_size - stack_get_top(stack)) / 2;
    *(out) = (int32_t) deleted_pair_len, (*o_len) ++;
    *(out + 1) = (int32_t) stack_get_top(stack), (*o_len) ++;

finish:
    stack_free(stack);
    return ret;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170783 https://github.com/carloscn/structstudy/commit/fb745c0c3726d1187c55d71b3a76f05466bf52dc