problem
453. Minimum Moves to Equal Array Elements
相当于把不等于最小值的数字都减到最小值所需要次数的累加和。
solution1:
class Solution {
public:
int minMoves(vector<int>& nums) {
int res = ;//err-initialization.
int mn = INT_MAX;//err.
for(auto num:nums) mn = min(num, mn);
for(auto num:nums) res += num-mn;
return res;
}
};
记得初始化,否则默认初始值是最小值。
solution2:
换一种思路,就是数组之和减去最小值乘以数组长度之积。
class Solution {
public:
int minMoves(vector<int>& nums) {
int mn = INT_MAX;
long sum = ;
for(int num:nums)
{
mn = min(num, mn);
sum += num;
}
return sum-mn*nums.size();
}
};
参考
1. Leetcode_453. Minimum Moves to Equal Array Elements;
2. GrandYang;
完