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,问操作多少次可以使所有的数相等。时间复杂度O(n)
数学题0.0设数组中所有数的和为sum,n为数组的长度,操作了m次,最后所有数都变成x,则有
sum + m * (n - 1) = x * n
x = mmin + m
m = sum - mmin * n
class Solution {
public:
int minMoves(vector<int>& nums) {
int n = nums.size();
if (n <= 1) return 0;
int sum = 0;
int mmin = nums[0];
for (auto x: nums) {
sum += x;
mmin = min(mmin, x);
}
return sum - mmin * n;
}
};
462. Minimum Moves to Equal Array Elements II
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:
Input: [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2]
每次操作可以把一个数+1或者-1,问多少次操作可以使数组中数都相等。
选择一个中位数,然后让所有的数都等于这个数即可。排序之后,从两边往中间走,大值和小值之间的差距,是一定要填补上的,不管+1 还是 -1,所以最后都等于中位数。
class Solution {
public:
int minMoves2(vector<int>& nums) {
int n = nums.size();
if (n <= 1) return 0;
sort(nums.begin(), nums.end());
int sum = 0;
int i = 0, j = n - 1;
while (i < j) {
sum += nums[j]- nums[i];
i++;
j--;
}
return sum;
}
};