问题描述:
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.
示例:
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]
问题分析:
这类问题实际是求出数组的中位数,然后累加每个元素到中位数的距离。
过程详见代码:
class Solution {
public:
int minMoves2(vector<int>& nums) {
int n = nums.size();
auto it = nums.begin() + n / 2;
nth_element(nums.begin(), it, nums.end());
int median = *it;
int total = 0;
for (auto &i : nums)
total += abs(i - median);
return total;
}
};