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].
分析:
实际上是排序然后隔项求和。快排。
static auto _____ = []() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
QuickSort(nums, 0, nums.size()-1);
int sum = 0;
for(int i = 0;i<nums.size();i+=2)
sum+=nums[i];
return sum;
}
void QuickSort(vector<int>& nums, int left, int right)
{
if(left < right)
{
int index = Pivot(nums, left, right);
QuickSort(nums, left, index-1);
QuickSort(nums, index+1, right);
}
}
int Pivot(vector<int>& nums, int left, int right)
{
int pivot = nums[left];
while(left < right)
{
while(right>left&&nums[right]>=pivot) --right;
nums[left] = nums[right];
while(right>left&&nums[left]<=pivot) ++left;
nums[right] = nums[left];
}
nums[left] = pivot;
return left;
}
};
后来看到一种更不错的,用来bitmap的思想,免去了排序,看题目的答案就好了,这里就不贴出。