Code & Func
2019-11-24

第20天。

今天的题目是 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:

1
Input:
2
[1,2,3]
3
4
Output:
5
2
6
7
Explanation:
8
Only two moves are needed (remember each move increments or decrements one element):
9
10
[1,2,3] => [2,2,3] => [2,2,2]

这道题需要一些数学推导,它的目标就是:

$$ min_k { \sum_{i=1}^n |n_i - n_k| } $$ 其中 $n_i$ 表示数组排序后中第 $i$ 个元素。

我们将式子展开可以得到: $$ min_k { \sum_{i=1}^n |n_i - n_k| } =

min_k { \sum_{i=1}^k (n_k-n_i) + \sum_{i=k+1}^n(n_i-n_k) } \

= min_k { \sum_{i=1}^k n_k - \sum_{i=1}^k n_i + \sum_{i=k+1}^n n_i - \sum_{i=k+1}^n n_k } \

= min_k { \sum_{i=k+1}^n n_i - \sum_{i=1}^k n_i + (2k - n)n_k } $$ 因此,我们可以写出如下代码:

1
int minMoves2(vector<int>& nums) {
2
long long res = LONG_MAX;
3
sort(nums.begin(), nums.end());
4
long long rightSum = 0;
5
for(auto i: nums) rightSum += i;
6
long long leftSum = 0;
7
int n = nums.size();
8
9
for(int i = 0;i < n; ++i) {
10
res = min(res, rightSum - leftSum + (2*i - n) * (long long)nums[i]);
11
rightSum -= nums[i];
12
leftSum += nums[i];
13
// cout << res << endl;
14
}
15
2 collapsed lines
16
return res;
17
}

这样还不是最优解,然而最优解我没看懂(捂脸),为什么用中位数求就是对的呢?:

1
int minMoves2(vector<int>& nums) {
2
3
sort(nums.begin(), nums.end());
4
5
int mid;
6
7
if (nums.size() % 2 == 0){
8
9
mid = (nums[nums.size()/2] + nums[(nums.size()/2) - 1])/2;
10
11
}else{
12
13
mid = nums[nums.size()/2];
14
15
}
12 collapsed lines
16
17
int result = 0;
18
19
for (int i = 0; i < nums.size(); i++){
20
21
result += abs(nums[i] - mid);
22
23
}
24
25
return result;
26
27
}
上一条动态