题目:
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.
题意:
给出一个长度为2n的数组,将他们两个一组,分为n组,求每一组中的较小值,求这些较小值相加的最大和。
输入输入样例:
Input: [1,4,3,2]Output: 4Explanation: 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].
Python 解:
思路:使用自带函数sorted排序,将索引为0,2,4,6....n-2的数相加(即奇数顺序的数),时间复杂度为nlog(n)
class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ return sum(sorted(nums)[::2])
C++解:
思路:时间复杂度为 O(n),说是哈希,但其实是桶排序,桶排序和哈希排序主要思想都差不多,使用flag 跳过偶数 只相加奇数,因为有负数所以+10000
用空间换时间,
语法要点:使用了vector容器,vector<int>& nums直接将 nums 数组赋值给vector容器。
vector意为向量,可以理解为数组的增强版,封装了许多对自身操作的函数。
class Solution {public: int arrayPairSum(vector & nums) { int ret = 0; bool flag = true; arrayhashtable{ 0 }; for (const auto n : nums) { ++hashtable[n + 10000]; } for (int i = 0; i < 20001;) { if (hashtable[i] > 0) { if (flag) { flag = false; ret += (i - 10000); --hashtable[i]; } else { flag = true; --hashtable[i]; } } else ++i; } return ret; }};