Topic:
Given an array of 2n integers, your task was 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.
Test instructions
Give an array of length 2n, divide them into groups of N, and ask for smaller values in each group to find the maximum sum of these smaller values.
Enter an input sample:
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 (positive integer), which is in the range of [1, 10000].
- All the integers in the array would be in the range of [-10000, 10000].
Python Solution:
Idea: Use the sorted function to sort, add the number of indexes to 0,2,4,6....n-2 (that is, the number of odd orders), the time complexity is Nlog (n)
class solution (Object): def arraypairsum (Self, nums): """ : Type Nums:list[int] : rtype:int "" " return sum (sorted (nums) [: : 2])
C + + Solution:
Idea: don't understand, time complexity is O (n)
Syntax essentials: Using the vector container,vector<int>& nums directly assigns the nums array to the vector container.
Vector, which can be understood as an enhanced version of the array, encapsulates a number of functions that operate on its own.
classSolution { Public: intArraypairsum (vector<int>&nums) { intRET =0; BOOLFlag =true; Array<int,20001> hashtable{0 }; for(ConstAuto N:nums) { ++hashtable[n +10000]; } for(inti =0; I <20001;) { if(Hashtable[i] >0) { if(flag) {flag=false; RET+ = (I-10000); --Hashtable[i]; } Else{flag=true; --Hashtable[i]; } } Else++i; } returnret; }};
Algorithm--leetcode 561. Array Partition I