给定一个长度为 n 的非空整数数组,找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。
示例:
输入: [1,2,3] 输出: 3 解释: 只需要3次移动(注意每次移动会增加两个元素的值): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
逆向思考,让n-1个数+1不就等价于让一个数-1吗,那不就是把其他数砍到和最小数一样小不就都相等了吗,这个砍了几次呢???
class Solution {
public int minMoves(int[] nums) {
int sum=0;
int min = Integer.MAX_VALUE;
for(int x:nums){
sum+=x;
if(x<min)
min = x;
}
return sum - min*nums.length;
}
}
在任何移动之前,让我们将sum定义为所有数字的总和; minNum作为列表中的最小数字; n是列表的长度;
之后,比如m移动,我们得到所有数字为x,我们将得到以下等式
sum + m * (n - 1) = x * n
实际上,
x = minNum + m
这部分可能有点混乱,但@shijungg解释得很好。让我再解释一下。它来自两个观察结果:
- 最小数量将始终为最小值,直到达到最终数字,因为每次移动,其他数字(除了最大值)也会增加;
- 从上面我们可以得到,最小数量将在每一步中递增。所以,如果最终的数字是x,那么minNum +移动;
最后,我们会得到
sum - minNum * n = m
这只是一个数学计算。
let's define sum as the sum of all the numbers, before any moves; minNum as the min number int the list; n is the length of the list;
After, say m moves, we get all the numbers as x , and we will get the following equation
sum + m * (n - 1) = x * n
and actually,
x = minNum + m
This part may be a little confusing, but @shijungg explained very well. let me explain a little again. it comes from two observations:
- the minum number will always be minum until it reachs the final number, because every move, other numbers (besides the max) will be increamented too;
- from above, we can get, the minum number will be incremented in every move. So, if the final number is x, it would be minNum + moves;
and finally, we will get
sum - minNum * n = m
This is just a math calculation.
解决方案没有错,但推理不正确:总有一个解决方案并不明显; 您提供的解决方案都不是最佳的。
有效地将1添加到n - 1个元素相当于从1个元素中减去1。因此,问题转换为:每个步骤允许从1个元素中删除1,并且您的目标是使所有元素相等。
去除后,总和为minNum * n,因此所需步数为sum - minNum * n。The solution is not wrong, but the reasoning is not right: it is not obvious that there is always a solution; neither the solution you provide is optimal.
Adding 1s to n - 1 elements effectively is equivalent to subtracting 1 from 1 element. Therefore the question is transformed to: you are allowed to remove 1 from 1 element each steps, and your goal is to make all element equal.
After the removal, total sum is minNum * n, hence the number of step needed is sum - minNum * n.