给定一个长度为 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。 加一:[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 减一:[1,2,3] => [1,2,2] => [1,1,2] => [1,1,1] 所以先求出最小的元素,在求出所有元素与最小元素的差值的和,即为最小移动次数。 复制代码
实现:
class Solution {
public int minMoves(int[] nums) {
int min = nums[0];
int count = 0;
for(int i = 0;i<nums.length;i++){
min = Math.min(nums[i],min);
}
for(int i = 0;i<nums.length;i++){
count += nums[i] - min;
}
return count;
}
}复制代码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Discrete Mathematics and Its Applications
Kenneth H Rosen / McGraw-Hill Science/Engineering/Math / 2003-04-22 / USD 132.81
Discrete Mathematics and its Applications is a focused introduction to the primary themes in a discrete mathematics course, as introduced through extensive applications, expansive discussion, and deta......一起来看看 《Discrete Mathematics and Its Applications》 这本书的介绍吧!