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;
}
}
本文介绍了一种算法,用于寻找使数组所有元素相等所需的最小移动次数,通过递增n-1个元素来实现。文章提供了逆向思考的方法,并附带了一个Java实现的例子。

159

被折叠的 条评论
为什么被折叠?



