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]Solution:
class Solution {
public:
int minMoves(vector<int>& nums) {
int min = nums[0];
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
if (min > nums[i]) {
min = nums[i];
}
}
return sum - nums.size() * min;
}
};
我当时就是这么想的,题目意思等同于:每个数都加一后其中一个数减一,那么要让每个数相等,最终就会是每个数都等于最小的那个数。那么要求最小次数就是每个数减去最小数,再求和。