題目:
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.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].題目大意:
給定一個(gè)2n個(gè)整數(shù)的數(shù)組,你的任務(wù)是將這些整數(shù)分成n對(duì)整數(shù),例如(a 1,b 1),(a 2,b 2),...,(a n,b n)所有i從1到n 的最?。╝ i,b i)的和盡可能大。
示例1: 輸入: [1,4,3,2] 輸出: 4 說(shuō)明: n為2,最大對(duì)數(shù)為4。注意:
n是正整數(shù),在[1,10000]的范圍內(nèi)。
數(shù)組中的所有整數(shù)將在[-10000,10000]的范圍內(nèi)。
解題思路
題目大意為要將2n個(gè)數(shù)最終形成n個(gè)數(shù)對(duì),每個(gè)數(shù)對(duì)中最小元素的和最大。
即取數(shù)對(duì)中較小的元素,并且要求和最大。
所以要求數(shù)對(duì)的元素之間的差值盡可能小,這樣選取小數(shù)據(jù)時(shí),損失不會(huì)太大。
所以只需將數(shù)組進(jìn)行排序,排序后將對(duì)較小的元素進(jìn)行求和就好了
具體實(shí)現(xiàn)
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int min = 0;
for(int i=0; i < nums.size(); i=i+2)
{
min += nums[i];
}
return min;
}
};