LeetCode 题解工作台
合并两个二维数组 - 求和法
给你两个 二维 整数数组 nums1 和 nums2. nums1[i] = [id i , val i ] 表示编号为 id i 的数字对应的值等于 val i 。 nums2[i] = [id i , val i ] 表示编号为 id i 的数字对应的值等于 val i 。 每个数组都包含 互不…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用一个哈希表或数组 `cnt` 统计两个数组中每个数字出现的次数。 然后我们从小到大枚举 `cnt` 中的每个数字,如果该数字出现的次数大于 ,则将其加入答案数组中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你两个 二维 整数数组 nums1 和 nums2.
nums1[i] = [idi, vali]表示编号为idi的数字对应的值等于vali。nums2[i] = [idi, vali]表示编号为idi的数字对应的值等于vali。
每个数组都包含 互不相同 的 id ,并按 id 以 递增 顺序排列。
请你将两个数组合并为一个按 id 以递增顺序排列的数组,并符合下述条件:
- 只有在两个数组中至少出现过一次的 id 才能包含在结果数组内。
- 每个 id 在结果数组中 只能出现一次 ,并且其对应的值等于两个数组中该 id 所对应的值求和。如果某个数组中不存在该 id ,则假定其对应的值等于
0。
返回结果数组。返回的数组需要按 id 以递增顺序排列。
示例 1:
输入:nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]] 输出:[[1,6],[2,3],[3,2],[4,6]] 解释:结果数组中包含以下元素: - id = 1 ,对应的值等于 2 + 4 = 6 。 - id = 2 ,对应的值等于 3 。 - id = 3 ,对应的值等于 2 。 - id = 4 ,对应的值等于 5 + 1 = 6 。
示例 2:
输入:nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]] 输出:[[1,3],[2,4],[3,6],[4,3],[5,5]] 解释:不存在共同 id ,在结果数组中只需要包含每个 id 和其对应的值。
提示:
1 <= nums1.length, nums2.length <= 200nums1[i].length == nums2[j].length == 21 <= idi, vali <= 1000- 数组中的 id 互不相同
- 数据均按 id 以严格递增顺序排列
解题思路
方法一:计数 + 枚举
我们可以用一个哈希表或数组 cnt 统计两个数组中每个数字出现的次数。
然后我们从小到大枚举 cnt 中的每个数字,如果该数字出现的次数大于 ,则将其加入答案数组中。
时间复杂度 ,空间复杂度 。其中 和 分别是两个数组的长度;而 是两个数组中数字的最大值,本题中 。
class Solution:
def mergeArrays(
self, nums1: List[List[int]], nums2: List[List[int]]
) -> List[List[int]]:
cnt = Counter()
for i, v in nums1 + nums2:
cnt[i] += v
return sorted(cnt.items())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N1 + N2) due to scanning each array once. Space complexity is O(N1 + N2) if storing results in a new array or using a hash map. |
| 空间 | O(N1 + N2) |
面试官常问的追问
外企场景- question_mark
Will the candidate notice the arrays are sorted and avoid unnecessary nested loops?
- question_mark
Does the candidate use a hash map or two-pointer approach to merge efficiently?
- question_mark
Is summing values correctly applied when ids overlap without losing any unique ids?
常见陷阱
外企场景- error
Failing to sum values for ids appearing in both arrays.
- error
Using nested loops which lead to O(N1 * N2) time instead of O(N1 + N2).
- error
Not maintaining ascending order in the merged array.
进阶变体
外企场景- arrow_right_alt
Arrays with duplicate ids within themselves requiring internal aggregation first.
- arrow_right_alt
Arrays containing strings as values instead of integers for merging.
- arrow_right_alt
Merging more than two arrays in sequence using the same sum-by-id pattern.