# 453. Minimum Moves to Equal Array Elements 最小操作次数使数组元素相等

@TOC

[LeetCode]

• Difficulty: Easy

## # 题目描述

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]
``````

## # 解题方法

### # 方法一：模拟过程

``````public class Solution {
public int minMoves(int[] nums) {
int count=0;
Arrays.sort(nums);
while(nums[0] != nums[nums.length-1]){
for(int i=0; i<nums.length-1; i++){
nums[i]++;
}
Arrays.sort(nums);
count++;
}
return count;
}
}
``````

### # 方法二：求和-n*最小值

``````public class Solution {
public int minMoves(int[] nums) {
int count=0;
int min=nums[0];
for(int num : nums){
min=Math.min(min,num);
}
for(int num : nums){
count += num - min;
}
return count;
}
}
``````

AC: 14 ms

python的代码如下：

``````class Solution:
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(nums) - len(nums) * min(nums)
``````

C++代码如下：

``````class Solution {
public:
int minMoves(vector<int>& nums) {
int mn = INT_MAX;
long long s = 0;
for (int n : nums) {
if (n < mn) mn = n;
s += n;
}
return s - nums.size() * mn;
}
};
``````

### # 方法三：排序

``````public class Solution {
public int minMoves(int[] nums) {
int count=0;
Arrays.sort(nums);
for(int num : nums){
count += num - nums[0];
}
return count;
}
}
``````

AC:53 ms

python代码如下：

``````class Solution:
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
res = 0
for num in nums:
res += num - nums[0]
return res
``````

## # 日期

2017 年 1 月 7 日 2018 年 11 月 14 日 —— 很严重的雾霾 2018 年 12 月 14 日 —— 12月过半，2019就要开始