0%

minimum-moves-to-equal-array-elements

Minimum Moves to Equal Array Elements – LeetCode 453

Problem

Description

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]

Answer

Original

Code

1
2
3
4
5
6
7
8
9
class Solution {
public:
int minMoves(vector<int>& nums) {
int mn = INT_MAX, res = 0;
for (int num : nums) mn = min(mn, num);
for (int num : nums) res += num - mn;
return res;
}
};

思路

给n-1个元素加一相当与给指定的元素减一。于是只要把相对于最小的数都剪掉就行了。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$52$ ms,排名$45.25\%$

Better

思路

还没看到更好的思路。