solution:
先排序,选择中位数进行移动。
假设一组数 1 3 7 10 5,排完序后 1 3 5 7 10,中位数为5,答案ans = (5 - 1) + (3 - 1) + (7 - 5) + (10 - 5) = 13 = (10 - 1) + (7 - 3)
class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(),nums.end());
int i = 0,j = nums.size() - 1;
int ans = 0;
while(i < j) {
ans += nums[j--] - nums[i++];
}
return ans;
}
};