[LeetCode]561. Array Partition I

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:

1
2
3
4
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].

题目解释:

  • 输入:一个无序数组,包含一偶数个数的数字;
  • 输出:2n个数,分成n组,每组里面找到最小值,所有最小值加起来,得到和的最大值。

方法一

思路:要先得到最小值,又要得到和的最大值,先给数组排序,每两个一组,直接取偶数位的数字相加即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int out = 0;
for(int i = 0; i < nums.size(); ++i) {
if ((i & 1) != 1) {
out += nums[i];
}
}
return out;
}
};

result

Runtime: 76 ms, faster than 78.80% of C++ online submissions for Array Partition I.

Memory Usage: 11.2 MB, less than 70.64% of C++ online submissions for Array Partition I.

方法二

没必要判断奇偶数,直接把index+2即可,但是效率差别不大;

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int out = 0;
for(int i = 0; i < nums.size(); i+=2) {
out += nums[i];
}
return out;
}
};

result

Runtime: 72 ms, faster than 88.11% of C++ online submissions for Array Partition I.

Memory Usage: 11.4 MB, less than 48.75% of C++ online submissions for Array Partition I.