Description:
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
Note:
n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000].
这道题在LeeCode上是一道简单的数组题,由于是我做的第一道算法题,所以我非常的慎重,把题目翻译了好几遍(英语渣用的机器翻译)
大概意思
给你一个2n的整型数组,然后两两分组,问:如何分 才能使每个 分组的最小值 的和 相加最大?
注:
n是一个正整数,且n的范围是[1,10000]
数组中的整数范围是[-10000, 10000]
怎么做呢?先举个栗子:
假设n=2,给定的数组为[1,2,3,4],可以分为以下三组:
[1,2] [3,4]
[1,3] [2,4]
[1,4] [2,3]
我们可以得出一些规律:
- 1在这个数组中是最小值,无论分在哪个组中,都会参与最终的运算
- 4在这个数组中是最大值,无论分在哪个组中,都不会参与最终的运算
- 除去这两个特殊的值,其它的所有值是否参与最终运算都是不确定的
得出结论
我把第二大的元素跟不会参与运算的最大值放在一块分为一组,然后除去分完组的元素,剩下的元素又成为一个新的数组,依次类推。分组到最后就会发现,其实就是一个有序列表,从大到小(或从小到大),依次两两分组。
于是上代码
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int i, sum = 0;
for (i = 0; i < nums.length; i = i + 2) {
sum += nums[i];
}
return sum;
}
解法很完美,暗自窃喜一波儿,提交代码,大功告成。
。
。
。
。
。
。
上面的方法思路太平淡,显然不是最优解法
最优解贴出来,等我参透了再来更新
public int optimumSolution(int[] nums) {
int[] t = new int[20001];
for (int i = 0; i < nums.length; i++) {
t[nums[i] + 10000]++;
}
int n = nums.length / 2;
int sum = 0;
int carry = 0;
for (int i = 20000; i >= 0 && n > 0; i--) {
if (t[i] == 0) continue;
int val = i - 10000;
int canBeUsed = (t[i] + carry) / 2;
carry = (t[i] + carry) % 2;
int x = Math.min(n, canBeUsed);
n -= x;
sum += x * val;
}
return sum;
}
算法的魅力也许就在于此,当你满心欢喜的解出一道题时,却总是有更好的解法在等着你