LeetCode 题解工作台
最小操作次数使数组元素相等
给你一个长度为 n 的整数数组,每次操作将会使 n - 1 个元素增加 1 。返回让数组所有元素相等的最小操作次数。 示例 1: 输入: nums = [1,2,3] 输出: 3 解释: 只需要3次操作(注意每次操作会增加两个元素的值): [1,2,3] => [2,3,3] => [3,4,3] …
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们不妨记数组 的最小值为 ,数组的和为 ,数组的长度为 。 假设最小操作次数为 ,最终数组的所有元素都为 ,则有:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个长度为 n 的整数数组,每次操作将会使 n - 1 个元素增加 1 。返回让数组所有元素相等的最小操作次数。
示例 1:
输入:nums = [1,2,3] 输出:3 解释: 只需要3次操作(注意每次操作会增加两个元素的值): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
示例 2:
输入:nums = [1,1,1] 输出:0
提示:
n == nums.length1 <= nums.length <= 105-109 <= nums[i] <= 109- 答案保证符合 32-bit 整数
解题思路
方法一:数学
我们不妨记数组 的最小值为 ,数组的和为 ,数组的长度为 。
假设最小操作次数为 ,最终数组的所有元素都为 ,则有:
将第二个式子代入第一个式子,得到:
因此,最小操作次数为 。
时间复杂度 ,空间复杂度 。其中 为数组的长度。
class Solution:
def minMoves(self, nums: List[int]) -> int:
return sum(nums) - min(nums) * len(nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because it requires a single pass to find the minimum and sum differences. Space complexity is O(1) extra space as no additional structures are needed beyond variables. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate quickly identifies the pattern of incrementing n-1 elements as equivalent to decrementing one element.
- question_mark
They recognize that tracking sum differences relative to the minimum yields an immediate solution.
- question_mark
They avoid simulating each move, showing awareness of efficient array plus math strategies.
常见陷阱
外企场景- error
Simulating every increment individually instead of computing the total mathematically.
- error
Failing to account for negative numbers in the array when calculating moves.
- error
Assuming the target is the maximum element rather than aligning all elements relative to the minimum.
进阶变体
外企场景- arrow_right_alt
Change the move operation to increment k elements instead of n-1 and recalculate minimum moves.
- arrow_right_alt
Allow decrementing n-1 elements in a move and compare with the increment variant for efficiency.
- arrow_right_alt
Apply the pattern to multi-dimensional arrays where each move adjusts n-1 cells along a row or column.