您的位置:首页 > 其它

Leetcode 453 Minimum Moves to Equal Array Elements

2016-11-29 14:38 711 查看
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-1的时候相当于把最大的元素减1 等到所有的元素都减到和最小元素相等的时候 就是符合题目要求的时候
逆向思维很重要啊

public class Solution {
public int minMoves(int[] nums) {
int sum = 0;
int n= nums.length;
Arrays.sort(nums);
for(int i =0;i<n;i++){
sum+=nums[i]-nums[0];
}

return sum;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: