Problem
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].
Solution 1: Sorting
Time complexity: O(nlogn)
Space complexity: O(1)
| 1 2 3 4 5 6 7 8 9 10 11 12 | // Author: Huahua // Running time: 52 ms class Solution { public:   int arrayPairSum(vector<int>& nums) {     std::sort(nums.begin(), nums.end());     int ans = 0;     for(int i = 0; i < nums.size(); i += 2)         ans += nums[i];     return ans;   } }; | 
Solution 2: HashTable
Time complexity: O(n + max(nums) – min(nums))
Space complexity: O(max(nums) – min(nums))
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // Author: Huahua // Running time: 39 ms class Solution { public:   int arrayPairSum(vector<int>& nums) {     const int max_val = *max_element(begin(nums), end(nums));     const int min_val = *min_element(begin(nums), end(nums));     const int offset = -min_val;     vector<int> c(max_val - min_val + 1);     for (int num : nums)         ++c[num + offset];     int ans = 0;     int index = 0;     int n = min_val;     while (n <= max_val) {       if (c[n + offset] == 0) {         ++n;         continue;       }       ans += (++index & 1) ? n : 0;       --c[n + offset];     }     return ans;   } }; | 
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.



Be First to Comment