题目地址

解题思路

看到这道题,想到的是将数组排序,然后用最大值 - 最小值,得到的差值进行比较,当差值 等于 0,循环结束,返回得到的次数。代码如下:

代码

  1. const getCount = (nums,n,c)=>{
  2. nums.sort((a,b)=>a-b)
  3. let max = Math.max(...nums),min = Math.min(...nums);
  4. let dist = max - min;
  5. if(dist == 0 ) return c;
  6. c += dist;
  7. for(let i = 0;i<n-1;i++){
  8. nums[i] += dist;
  9. }
  10. return getCount(nums,n,c);
  11. }
  12. var minMoves = function(nums) {
  13. let count = 0,n = nums.length;
  14. return getCount(nums,n,count);
  15. };
  16. const nums = [1,2,3,4];

问题

但是没通过,超时了,看了题解,代码很简单,但是有点不太理解,题解代码如下:

image.png

  1. var minMoves = function(nums) {
  2. const minNum = Math.min(...nums);
  3. let res = 0;
  4. for (const num of nums) {
  5. res += num - minNum;
  6. }
  7. return res;
  8. };