p453

LeetCode p453 Minimum Moves to Equal Array Elements 题解

1.题目:

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]

题意:

输入一个长度为n的数组,每次操作对数组中n-1个数加一,问至少多少次操作之后可以让数组中每个数都相等。

2.解题思路:

每次操作对数组中n-1个数加一,等同与对数组中一个数减1,最后使他们全部相等。
所以只需要累加数组中每个数和最小值中的差值就可以了。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
 
public class Solution {
public int minMoves(int[] nums) {
long ans = 0;
Arrays.sort(nums);
int min = nums[0];
for (int a : nums) {
ans += a - min;
}
return (int) ans;
}
}

4.一些总结: