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,相当于一个元素每次减1,累加各个元素与数组最小元素差值即可。
/**
* @param {number[]} nums
* @return {number}
*/
const minMoves = function (nums) {
// find minimum value
const findMinimumValue = function(nums) {
let minimum = nums[0];
for(let num of nums) {
if(num < minimum) {
minimum = num;
}
}
return minimum;
};
let moves = 0;
let minimum = findMinimumValue(nums);
for(let i=0;i<nums.length;i++) {
moves += nums[i] - minimum;
}
return moves;
};
时间复杂度为O(n),空间复杂度为O(1)