leetcode
leetcode 2251 ~ 2300
从两个数字数组里生成最小数字

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

难度:

标签:

题目描述

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.

代码结果

运行时间: 22 ms, 内存: 16.0 MB


/*
思路:
1. 找出两个数组中都包含的数字,返回最小的那个。
2. 如果没有公共数字,则返回由两个数组中最小的数字组成的两位数。
*/
import java.util.*;
import java.util.stream.*;

public class Solution {
    public int minNumber(int[] nums1, int[] nums2) {
        // 找出两个数组中的最小值
        int min1 = Arrays.stream(nums1).min().getAsInt();
        int min2 = Arrays.stream(nums2).min().getAsInt();

        // 用一个集合来存储 nums1 中的数字
        Set<Integer> set = Arrays.stream(nums1).boxed().collect(Collectors.toSet());

        // 查找 nums2 中的最小公共数字
        OptionalInt minCommon = Arrays.stream(nums2).filter(set::contains).min();

        // 如果找到了公共数字,则返回最小的公共数字
        if (minCommon.isPresent()) return minCommon.getAsInt();

        // 如果没有找到公共数字,则返回由最小的两个数字组成的两位数
        return Math.min(min1 * 10 + min2, min2 * 10 + min1);
    }
}

解释

方法:

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)

代码细节讲解

🦆
如何确定两个数组没有公共数字时,使用最小的数字组合成两位数的策略总是有效的?
当两个数组没有公共数字时,策略是分别找出每个数组中的最小数字,然后将这两个数字组合成一个两位数。为了保证组合后的数字是最小的,较小的数字被放在十位上,较大的数字放在个位上。这样可以确保不管两个最小数字的具体大小如何,组合后的两位数总是最小的可能值。例如,如果两个最小数字分别是3和5,组合后的数字为35,而不是53。这种策略有效,因为它直接根据数字的大小进行排序组合,确保了数字的最小性。
🦆
如果两个数组中的最小元素相同,比如nums1和nums2中都是最小元素3,解决方案如何处理?
题目中说明每个数组中的元素互不相同,但没有规定两个不同数组之间不能有相同的元素。在算法中,如果两个数组中的最小元素相同,这实际上意味着这个最小元素是一个公共元素。根据算法的逻辑,如果存在公共元素,则直接返回最小的公共元素。因此,如果nums1和nums2的最小元素相同,这个最小元素会被直接返回,不需要进一步组合成两位数。
🦆
为什么在没有公共数字时选择将较小的数字放在十位上,这种方法是否在所有情况下都能保证生成的数字是最小的?
将较小的数字放在十位上,是基于十进制数位的权重来考虑的。十位的权重是个位的十倍,因此为了使整个数字尽可能小,应该将较小的数放在权重更大的位置。这种方法在所有情况下都有效,因为它直接利用了数字位权重的基本数学原理。例如,如果有两个数字2和5,放置2在十位(形成25)明显比放置5在十位(形成52)得到的结果要小。这种策略在任何两个不同的数字组合中都能保证最终的数字是最小可能的。

相关问题