453. Minimum Moves to Equal Array Elements
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
Approach
- 这是一道很有趣的数学问题,给你一数组,让你将他们的数都相等,操作是每次给n-1个元素加一,然后求最少的次数。一开始会想着去模拟这个过程,不论你怎么模拟优化,都会超时,因为数据很大,只能通过数学方法去解,首先我们列一个等式,我们设最少要加m次,n个元素中最小的元素为minNum,n个元素和为sum,最后每个数为M,我们会得到一个等式:
sum+m*(n-1)=M*n
,又M=minNum+m
,最后解即为m=sum-n*minNum
,时间顿时降为O(n)。32ms
Code
class Solution {
public:
int minMoves(vector<int>& nums) {
int sum = 0, minn = INT_MAX,N=nums.size();
for (auto &n:nums) {
if (n < minn)minn = n;
sum += n;
}
return sum - minn*N;
}
};