carloscn / structstudy

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

leetcode2605: Form Smallest Number From Two Digit Arrays #426

Open carloscn opened 10 months ago

carloscn commented 10 months ago

Description

Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array.

Example 1:

Input: nums1 = [4,1,3], nums2 = [5,7] Output: 15 Explanation: The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have.

Example 2:

Input: nums1 = [3,5,2,6], nums2 = [3,1,7] Output: 3 Explanation: The number 3 contains the digit 3 which exists in both arrays.

Constraints:

1 <= nums1.length, nums2.length <= 9 1 <= nums1[i], nums2[i] <= 9 All digits in each array are unique.

carloscn commented 10 months ago

Analysis

static int32_t min_number(int32_t* nums1, size_t nums1_size, int32_t* nums2, size_t nums2_size)
{
    int32_t ret = 0;

    UTILS_CHECK_PTR(nums1);
    UTILS_CHECK_PTR(nums2);

    int32_t min_1 = INT32_MAX;
    int32_t min_2 = INT32_MAX;
    int32_t common = INT32_MAX;
    if ((0 == nums1_size) &&
        (0 == nums2_size)) {
        goto finish;
    }

    for (size_t i = 0; i < nums1_size; i ++) {
        int32_t e = nums1[i];
        min_1 = UTILS_MIN(e, min_1);
        for (size_t j = 0; j < nums2_size; j ++) {
            min_2 = UTILS_MIN(nums2[j], min_2);
            if (e == nums2[j]) {
                common = (common > e) ? e : common;
            }
        }
    }

    if (common == INT32_MAX) {
        if (min_1 > min_2) {
            ret = min_2 * 10 + min_1;
        } else {
            ret = min_1 * 10 + min_2;
        }
    } else {
        ret = common;
    }

finish:
    return ret;
}
carloscn commented 10 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1172339 https://github.com/carloscn/structstudy/commit/6e70f535a0534198add1cef416725d6de7f04d64