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 | Input: [1,4,3,2] |
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].
题目解释:
- 输入:一个无序数组,包含一偶数个数的数字;
- 输出:2n个数,分成n组,每组里面找到最小值,所有最小值加起来,得到和的最大值。
方法一
思路:要先得到最小值,又要得到和的最大值,先给数组排序,每两个一组,直接取偶数位的数字相加即可。
1 | class Solution { |
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 | class Solution { |
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.