difficult:easy #561
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].
解法:
#include<vector>
void quicksort(std::vector<int> & array, int left, int right);
int arrayPairSum(std::vector<int>& nums) {
int result = 0;
quicksort(nums, 0, nums.size() - 1);
for (int i = 0; i < nums.size(); i += 2) {
result += nums[i];
}
return result;
}
void quicksort(std::vector<int> & array, int left, int right){
int i, j, t, temp;
if (left > right)
return;
temp = array[left];
i = left;
j = right;
while (i != j){
while (array[j] >= temp && i < j)
j--;
while (array[i] <= temp && i < j)
i++;
if (i<j) {
t = array[i];
array[i] = array[j];
array[j] = t;
}
}
array[left] = array[i];
array[i] = temp;
quicksort(array, left, i - 1);
quicksort(array, i + 1, right);
}
版权声明:原创,转载请注明来源,否则律师函警告
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!