解题思路
看到这道题,想到的是将数组排序,然后用最大值 - 最小值,得到的差值进行比较,当差值 等于 0,循环结束,返回得到的次数。代码如下:
代码
const getCount = (nums,n,c)=>{
nums.sort((a,b)=>a-b)
let max = Math.max(...nums),min = Math.min(...nums);
let dist = max - min;
if(dist == 0 ) return c;
c += dist;
for(let i = 0;i<n-1;i++){
nums[i] += dist;
}
return getCount(nums,n,c);
}
var minMoves = function(nums) {
let count = 0,n = nums.length;
return getCount(nums,n,count);
};
const nums = [1,2,3,4];
问题
但是没通过,超时了,看了题解,代码很简单,但是有点不太理解,题解代码如下:
var minMoves = function(nums) {
const minNum = Math.min(...nums);
let res = 0;
for (const num of nums) {
res += num - minNum;
}
return res;
};