LeetCode 题解工作台
数组的最小相等和
给你两个由正整数和 0 组成的数组 nums1 和 nums2 。 你必须将两个数组中的 所有 0 替换为 严格 正整数,并且满足两个数组中所有元素的和 相等 。 返回 最小 相等和 ,如果无法使两数组相等,则返回 -1 。 示例 1: 输入: nums1 = [3,2,0,1,0], nums2 …
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们记把数组中的 视为 ,统计两个数组的和,分别记为 和 。不妨设 $s_1 \le s_2$。 - 如果 $s_1 = s_2$,那么答案就是 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你两个由正整数和 0 组成的数组 nums1 和 nums2 。
你必须将两个数组中的 所有 0 替换为 严格 正整数,并且满足两个数组中所有元素的和 相等 。
返回 最小 相等和 ,如果无法使两数组相等,则返回 -1 。
示例 1:
输入:nums1 = [3,2,0,1,0], nums2 = [6,5,0] 输出:12 解释:可以按下述方式替换数组中的 0 : - 用 2 和 4 替换 nums1 中的两个 0 。得到 nums1 = [3,2,2,1,4] 。 - 用 1 替换 nums2 中的一个 0 。得到 nums2 = [6,5,1] 。 两个数组的元素和相等,都等于 12 。可以证明这是可以获得的最小相等和。
示例 2:
输入:nums1 = [2,0,2,0], nums2 = [1,4] 输出:-1 解释:无法使两个数组的和相等。
提示:
1 <= nums1.length, nums2.length <= 1050 <= nums1[i], nums2[i] <= 106
解题思路
方法一:分情况讨论
我们记把数组中的 视为 ,统计两个数组的和,分别记为 和 。不妨设 。
- 如果 ,那么答案就是 。
- 如果 ,那么 中必须存在 ,才能使得两个数组的和相等,此时的答案就是 。否则,说明无法使两个数组的和相等,返回 。
时间复杂度 ,其中 和 分别是数组 和 的长度。空间复杂度 。
class Solution:
def minSum(self, nums1: List[int], nums2: List[int]) -> int:
s1 = sum(nums1) + nums1.count(0)
s2 = sum(nums2) + nums2.count(0)
if s1 > s2:
return self.minSum(nums2, nums1)
if s1 == s2:
return s1
return -1 if nums1.count(0) == 0 else s2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n + m) because each element in both arrays is processed once. Space complexity is O(1) since only sum tracking and incremental adjustments are needed, no extra data structures proportional to input size are used. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
They may ask why greedy adjustment ensures minimal sum rather than random replacements.
- question_mark
Expect discussion on edge cases where an array has no zeros but a smaller sum.
- question_mark
They might check if your approach scales for arrays of length 10^5 with high element values.
常见陷阱
外企场景- error
Replacing zeros with arbitrary large numbers instead of minimal increments, missing the minimal sum.
- error
Ignoring arrays with no zeros, leading to incorrect -1 detection.
- error
Failing to update sums correctly after each greedy increment, causing wrong final sums.
进阶变体
外企场景- arrow_right_alt
Allow zeros to be replaced with any integer including zero, changing the greedy strategy to account for non-positive replacements.
- arrow_right_alt
Instead of minimizing sum, maximize sum equality with constraints on maximum allowed element value.
- arrow_right_alt
Work with more than two arrays, extending greedy adjustments to multiple sums while maintaining the minimal total sum.