- Minimum Moves to Equal Array Elements II
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] => [2,2,3] => [2,2,2]
这里要想步骤最少,取得标准参考应该是数组的中位数。
证明:
先将数组按递增的顺序排好序
y1=∑i=0k(ak−ai)−∑i=k+1n(ai−ak),k≠n2
y2=∑i=0n2(an2−ai)−∑i=n2+1n(ai−an2)
假设 k>n2 ,即 ak=an2+x,x>0 ,
y1−y2=∑i=n2+1k(ak−ai)+n2×x+∑i=n2+1k(ai−an2)+(k−n)×x=∑i=n2+1k(ak−an2)+(k−n2)×x=(2k−n)×x>0
同理,当 ak<an2 时,也比 y2 大。
因此,如果取得不是中位数,最后的结果都会比这大。
int minMoves2(vector<int>& nums) {
int n=nums.size();
sort(nums.begin(),nums.end());
int r=0;
for(int i:nums)
r+=abs(i-nums[n/2]);
return r;
}