Problem: 462. 最小操作次数使数组元素相等 II
Code
c++
class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(),nums.end());
int len = nums.size();
int mid = len/2;
//sum前缀和
vector<long long> sum;
sum.push_back(0);
for(auto item:nums){
sum.push_back(sum.back()+item);
}
//return的地方画个柱状图分析一下就知道了
return (mid+1)*nums[mid]-sum[mid+1]+sum[len]-sum[mid]-(len-mid)*nums[mid];
}
};