【easy】561. Array Partition I

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:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].
class Solution {
public:
void quicksort(vector<int>& nums, int start, int end){//快排!!!
int i = start;
int j = end;
int x = nums[i];
if (start < end){
while (i<j)
{
while (nums[j]<x && i<j)
j--;
if (i<j)
nums[i++] = nums[j];
while (nums[i]>x && i<j)
i++;
if (i<j)
nums[j--] = nums[i];
}
nums[i] = x;
quicksort(nums, start, i-);
quicksort(nums, i+, end);
}
}
public:
int arrayPairSum(vector<int>& nums) {
//直接冒泡排序是超时的,所以考虑选择一个效率更高的排序
int len = nums.size();
quicksort(nums,,len-);
//贪心策略:排序选择偶数下标,相加
int sum = ;
for (int i=;i<len;i+=){
sum += nums[i];
}
return sum;
}
};
上一篇:about mobile web


下一篇:iTrash for Mac(卸载工具)破解版含注册机