LeetCode 题解工作台
使数组中所有元素相等的最小操作数 II
给你两个整数数组 nums1 和 nums2 ,两个数组长度都是 n ,再给你一个整数 k 。你可以对数组 nums1 进行以下操作: 选择两个下标 i 和 j ,将 nums1[i] 增加 k ,将 nums1[j] 减少 k 。换言之, nums1[i] = nums1[i] + k 且 num…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们用变量 记录加减次数的差值,用变量 记录操作次数。 遍历数组,对于每个位置 ,如果存在 并且 $a_i \neq b_i$,则无法使两个数组相等,返回 。否则,如果 $k \neq 0$,则 $a_i - b_i$ 必须是 的倍数,否则无法使两个数组相等,返回 。接下来,我们更新 和 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你两个整数数组 nums1 和 nums2 ,两个数组长度都是 n ,再给你一个整数 k 。你可以对数组 nums1 进行以下操作:
- 选择两个下标
i和j,将nums1[i]增加k,将nums1[j]减少k。换言之,nums1[i] = nums1[i] + k且nums1[j] = nums1[j] - k。
如果对于所有满足 0 <= i < n 都有 num1[i] == nums2[i] ,那么我们称 nums1 等于 nums2 。
请你返回使 nums1 等于 nums2 的 最少 操作数。如果没办法让它们相等,请你返回 -1 。
示例 1:
输入:nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3 输出:2 解释:我们可以通过 2 个操作将 nums1 变成 nums2 。 第 1 个操作:i = 2 ,j = 0 。操作后得到 nums1 = [1,3,4,4] 。 第 2 个操作:i = 2 ,j = 3 。操作后得到 nums1 = [1,3,7,1] 。 无法用更少操作使两个数组相等。
示例 2:
输入:nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1 输出:-1 解释:无法使两个数组相等。
提示:
n == nums1.length == nums2.length2 <= n <= 1050 <= nums1[i], nums2[j] <= 1090 <= k <= 105
解题思路
方法一:一次遍历
我们用变量 记录加减次数的差值,用变量 记录操作次数。
遍历数组,对于每个位置 ,如果存在 并且 ,则无法使两个数组相等,返回 。否则,如果 ,则 必须是 的倍数,否则无法使两个数组相等,返回 。接下来,我们更新 和 。
最后,如果 ,则无法使两个数组相等,返回 。否则,返回 。
时间复杂度 ,空间复杂度 。其中 为数组长度。
class Solution:
def minOperations(self, nums1: List[int], nums2: List[int], k: int) -> int:
ans = x = 0
for a, b in zip(nums1, nums2):
if k == 0:
if a != b:
return -1
continue
if (a - b) % k:
return -1
y = (a - b) // k
ans += abs(y)
x += y
return -1 if x else ans // 2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each element is processed once for difference and balancing checks. Space complexity is O(1) beyond input storage since only counters for surplus, deficit, and operations are maintained. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask about cases where differences cannot be reconciled due to modulo k incompatibility.
- question_mark
Check whether the candidate correctly computes total operations by summing divided differences.
- question_mark
Listen for explanation of greedy balancing between surplus and deficit elements.
常见陷阱
外企场景- error
Ignoring the modulo k check before attempting operations leads to incorrect results.
- error
Summing positive and negative differences without considering k may produce fractional operations.
- error
Failing to verify that total surplus equals total deficit can return impossible counts.
进阶变体
外企场景- arrow_right_alt
Change the operation to allow multiple indices simultaneously and analyze minimal total moves.
- arrow_right_alt
Restrict k to 1 and study performance on very large arrays, focusing on greedy correctness.
- arrow_right_alt
Allow nums1 and nums2 to contain negative numbers and observe modular arithmetic adjustments.