从两个数字数组里生成最小数字
难度:
标签:
题目描述
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)
代码细节讲解
🦆
如何确定两个数组没有公共数字时,使用最小的数字组合成两位数的策略总是有效的?
▷🦆
如果两个数组中的最小元素相同,比如nums1和nums2中都是最小元素3,解决方案如何处理?
▷🦆
为什么在没有公共数字时选择将较小的数字放在十位上,这种方法是否在所有情况下都能保证生成的数字是最小的?
▷