从两个数字数组里生成最小数字

标签: 数组 哈希表 枚举

难度: Easy

给你两个只包含 1 到 9 之间数字的数组 nums1 和 nums2 ,每个数组中的元素 互不相同 ,请你返回 最小 的数字,两个数组都 至少 包含这个数字的某个数位。

示例 1:

输入:nums1 = [4,1,3], nums2 = [5,7]
输出:15
解释:数字 15 的数位 1 在 nums1 中出现,数位 5 在 nums2 中出现。15 是我们能得到的最小数字。

示例 2:

输入:nums1 = [3,5,2,6], nums2 = [3,1,7]
输出:3
解释:数字 3 的数位 3 在两个数组中都出现了。

提示:

  • 1 <= nums1.length, nums2.length <= 9
  • 1 <= nums1[i], nums2[i] <= 9
  • 每个数组中,元素 互不相同 。

Submission

运行时间: 22 ms

内存: 16.0 MB

class Solution:
    def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
        c = set(nums1) & set(nums2)
        if c:
            return min(c)
        a,b = min(nums1),min(nums2)
        if a < b:
            return a * 10 + b
        return b * 10 + a

Explain

The solution first checks if there is a common digit between the two arrays using set intersection. If a common digit is found, the smallest common digit is returned as the result. If there is no common digit, the solution then finds the smallest digit in each array and forms the smallest possible two-digit number from these digits. The smaller digit is placed in the tens place and the larger digit in the units place to ensure the resulting number is the smallest possible.

时间复杂度: O(n + m)

空间复杂度: O(n + m)

class Solution:
    def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
        # Create sets from both lists to check for common digits
        c = set(nums1) & set(nums2)
        # If there's a common digit, return the smallest one
        if c:
            return min(c)
        # Find the smallest digit in each list
        a, b = min(nums1), min(nums2)
        # Form the smallest two-digit number from a and b
        if a < b:
            return a * 10 + b
        return b * 10 + a

Explore

当两个数组没有公共数字时,策略是分别找出每个数组中的最小数字,然后将这两个数字组合成一个两位数。为了保证组合后的数字是最小的,较小的数字被放在十位上,较大的数字放在个位上。这样可以确保不管两个最小数字的具体大小如何,组合后的两位数总是最小的可能值。例如,如果两个最小数字分别是3和5,组合后的数字为35,而不是53。这种策略有效,因为它直接根据数字的大小进行排序组合,确保了数字的最小性。

题目中说明每个数组中的元素互不相同,但没有规定两个不同数组之间不能有相同的元素。在算法中,如果两个数组中的最小元素相同,这实际上意味着这个最小元素是一个公共元素。根据算法的逻辑,如果存在公共元素,则直接返回最小的公共元素。因此,如果nums1和nums2的最小元素相同,这个最小元素会被直接返回,不需要进一步组合成两位数。

将较小的数字放在十位上,是基于十进制数位的权重来考虑的。十位的权重是个位的十倍,因此为了使整个数字尽可能小,应该将较小的数放在权重更大的位置。这种方法在所有情况下都有效,因为它直接利用了数字位权重的基本数学原理。例如,如果有两个数字2和5,放置2在十位(形成25)明显比放置5在十位(形成52)得到的结果要小。这种策略在任何两个不同的数字组合中都能保证最终的数字是最小可能的。