第一个问题:
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]
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,最终的情况是所有元素都是小的的元素
这个问题等价于将[1,2,3] => [1,1,1] 计算每个元素与最小元素的差值的和
int minMoves(vector<int>& nums) {
long long res=0;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++)
res+=nums[i]-nums[0];
return res;
}
第二个问题:
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]
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]
可以加,可以减,每次只操作一个元素,数组的中位数不变,先将数组排序,中位数左边的元素增加,中位数右边的元素减少
定义两个指针i和j,开始时,第一个指向数组第一个元素,第二个指向数组最后一个元素,
nums[j]-nums[i]就是使第i个元素和第j个元素相等需要的步数(由于可增可减,最后相等的值可以在区间[ nums[i],nums[j] ],任意取).然后执行i++,j--
当数组元素个数为奇数时,最中间的元素(中位数)就是最终确定的所有元素相等的那个值.
int minMoves2(vector<int>& nums) {
sort(nums.begin(),nums.end());
int i=0,j=nums.size()-1;
long long res=0;
while(i<j){
res+=nums[j]-nums[i];
i++;
j--;
}
return res;
}