问题描述:
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment n - 1 elements of the array by 1.
问题分析:
数组中n个数,我们每一次操作把其中的n-1个增加1,问经过多少次操作可以拉平所有的数。
其实就是一个简单的数学问题。直觉告诉我们这道题是小的数追击大的数的过程。既然涉及大小,我们就需要排序。从初始状态到结束状态,最小的数要先后追上所有的数,所以追击的路程之和为每个数与最小的数的差的sum。因为每次有n-1个数需要变动,所以有效追击路程每回合缩小1,所以需要sum(相当于追击路程/速度差)个回合完成追击
代码如下:
class Solution {
public int minMoves(int[] nums) {
Arrays.sort(nums);
int length=nums.length;
int ans=0;
for(int i=length-1; i>0; i--){
ans=ans+nums[i]-nums[0];
}
return ans;
}
}
时间复杂度: O(n)