LeetCode 题解工作台
使数组相似的最少操作次数
给你两个正整数数组 nums 和 target ,两个数组长度相等。 在一次操作中,你可以选择两个 不同 的下标 i 和 j ,其中 0 ,并且: 令 nums[i] = nums[i] + 2 且 令 nums[j] = nums[j] - 2 。 如果两个数组中每个元素出现的频率相等,我们称两个…
3
题型
5
代码语言
3
相关题
当前训练重点
困难 · 贪心·invariant
答案摘要
注意到,由于每次操作,元素的值只会增加 或减少 ,因此,元素的奇偶性不会改变。 因此,我们可以将数组 和 分别按奇偶性分为两组,分别记为 和 ,以及 和 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你两个正整数数组 nums 和 target ,两个数组长度相等。
在一次操作中,你可以选择两个 不同 的下标 i 和 j ,其中 0 <= i, j < nums.length ,并且:
- 令
nums[i] = nums[i] + 2且 - 令
nums[j] = nums[j] - 2。
如果两个数组中每个元素出现的频率相等,我们称两个数组是 相似 的。
请你返回将 nums 变得与 target 相似的最少操作次数。测试数据保证 nums 一定能变得与 target 相似。
示例 1:
输入:nums = [8,12,6], target = [2,14,10] 输出:2 解释:可以用两步操作将 nums 变得与 target 相似: - 选择 i = 0 和 j = 2 ,nums = [10,12,4] 。 - 选择 i = 1 和 j = 2 ,nums = [10,14,2] 。 2 次操作是最少需要的操作次数。
示例 2:
输入:nums = [1,2,5], target = [4,1,3] 输出:1 解释:一步操作可以使 nums 变得与 target 相似: - 选择 i = 1 和 j = 2 ,nums = [1,4,3] 。
示例 3:
输入:nums = [1,1,1,1,1], target = [1,1,1,1,1] 输出:0 解释:数组 nums 已经与 target 相似。
提示:
n == nums.length == target.length1 <= n <= 1051 <= nums[i], target[i] <= 106nums一定可以变得与target相似。
解题思路
方法一:奇偶分类 + 排序
注意到,由于每次操作,元素的值只会增加 或减少 ,因此,元素的奇偶性不会改变。
因此,我们可以将数组 和 分别按奇偶性分为两组,分别记为 和 ,以及 和 。
那么,我们只需要将 中的元素与 中的元素配对,将 中的元素与 中的元素配对,然后进行操作。配对的过程中,我们可以使用贪心的策略,每次将 中较小的元素与 中较小的元素配对,这样可以保证操作的次数最少。这里可以直接通过排序来实现。
由于每次操作,都可以将对应位置的元素差值减少 ,因此,我们累计每个对应位置的差值,最后除以 即可得到答案。
时间复杂度 ,其中 为数组 的长度。
class Solution:
def makeSimilar(self, nums: List[int], target: List[int]) -> int:
nums.sort(key=lambda x: (x & 1, x))
target.sort(key=lambda x: (x & 1, x))
return sum(abs(a - b) for a, b in zip(nums, target)) // 4
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks if you consider parity separately to avoid invalid operations.
- question_mark
Observes whether you identify that sum invariants guarantee feasibility of transformations.
- question_mark
Watches if you optimize operations using sorted differences rather than brute force.
常见陷阱
外企场景- error
Failing to separate even and odd numbers, causing impossible operations.
- error
Miscounting operations by not pairing differences optimally, leading to non-minimal results.
- error
Assuming identical sums of arrays is sufficient without verifying frequency alignment.
进阶变体
外企场景- arrow_right_alt
Allowing operations of ±k instead of ±2, requiring adjustment to the greedy pairing calculation.
- arrow_right_alt
Arrays with negative numbers, introducing additional parity and difference handling complexity.
- arrow_right_alt
Determining the minimum operations under a restricted set of indices instead of any two elements.