1 题目
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]
2 尝试解
2.1 分析
给定一个整型数组,每次操作允许对一个元素加减一。问多少次操作才能让这些数全部相等。
设最终全部相等时Xi = X, 那么要实现的目标就是min Sum(|Xi-X|)。显然,Xmin <= X <= Xmax,那么|Xmax-X|+|Xmin-X| = Xmax- Xmin,即要使最大值、最小值达到二者之间一个数,需要的总的操作是不变的,都是Xmax-Xmin。然后剩余数组成为一个规模更小的相同的问题。
2.2 代码
class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(),nums.end());
int min = 0;
int max = nums.size()-1;
int result = 0;
while(min < max){
result += nums[max]-nums[min];
min ++;
max --;
}
return result;
}
};
3 标准解
int minMoves2(vector<int>& nums) {
sort(nums.begin(), nums.end()); int n = nums.size(), res = 0;
for (int i = 0; i < n/2; ++i) res += (nums[n-1-i]-nums[i]);
return res;
}