LeetCode 题解工作台
使数组中所有元素相等的最小操作数
存在一个长度为 n 的数组 arr ,其中 arr[i] = (2 * i) + 1 ( 0 )。 一次操作中,你可以选出两个下标,记作 x 和 y ( 0 )并使 arr[x] 减去 1 、 arr[y] 加上 1 (即 arr[x] -=1 且 arr[y] += 1 )。最终的目标是使数组中的…
1
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数学·driven
答案摘要
根据题目描述,数组 是一个首项为 ,公差为 的等差数列。那么数组前 项的和为: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
存在一个长度为 n 的数组 arr ,其中 arr[i] = (2 * i) + 1 ( 0 <= i < n )。
一次操作中,你可以选出两个下标,记作 x 和 y ( 0 <= x, y < n )并使 arr[x] 减去 1 、arr[y] 加上 1 (即 arr[x] -=1 且 arr[y] += 1 )。最终的目标是使数组中的所有元素都 相等 。题目测试用例将会 保证 :在执行若干步操作后,数组中的所有元素最终可以全部相等。
给你一个整数 n,即数组的长度。请你返回使数组 arr 中所有元素相等所需的 最小操作数 。
示例 1:
输入:n = 3 输出:2 解释:arr = [1, 3, 5] 第一次操作选出 x = 2 和 y = 0,使数组变为 [2, 3, 4] 第二次操作继续选出 x = 2 和 y = 0,数组将会变成 [3, 3, 3]
示例 2:
输入:n = 6 输出:9
提示:
1 <= n <= 10^4
解题思路
方法一:数学
根据题目描述,数组 是一个首项为 ,公差为 的等差数列。那么数组前 项的和为:
由于一次操作中,一个数减一,另一个数加一,数组中所有元素的和不变。因此,数组中所有元素相等时,每个元素的值为 。那么,数组中所有元素相等所需的最小操作数为:
时间复杂度 ,其中 为数组长度。空间复杂度 。
class Solution:
def minOperations(self, n: int) -> int:
return sum(n - (i << 1 | 1) for i in range(n >> 1))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) because a direct formula computes the sum of differences for half the array. Space complexity is O(1) since no extra array is stored; calculations are arithmetic based on n. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect you to notice the array's sequential odd-number pattern.
- question_mark
Check if you compute target = sum(arr)/n before iterating.
- question_mark
Look for symmetry to minimize operations, not brute force each pair.
常见陷阱
外企场景- error
Trying to simulate each operation instead of using the sum formula.
- error
Ignoring symmetry and overcounting operations for mirrored elements.
- error
Miscomputing target as a middle element rather than the true average.
进阶变体
外企场景- arrow_right_alt
Arrays of even numbers instead of odd numbers but using the same operation rule.
- arrow_right_alt
Allowing operations that adjust elements by more than 1 unit per move.
- arrow_right_alt
Finding minimum operations when only adjacent elements can be adjusted.