561. Array Partition I

Question:

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:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].

Solution:

 1 class Solution {
 2 public:
 3     int arrayPairSum(vector<int>& nums) {
 4         vector<int>::size_type nsize=nums.size();//计算数组大小
 5         if(nsize==0){//如果大小为0,直接返回0
 6             return 0;
 7         }
 8         sort(nums.begin(),nums.end());//排序
 9         int sum=0;
10         for(int i=0;i<nsize;i+=2){//计算两两一组中,数小的那个,和即为结果
11             sum+=nums[i];
12         }
13         return sum;
14     }
15 };

题目直达:https://leetcode.com/problems/array-partition-i/

答案直达:http://www.itdadao.com/articles/c15a1321689p0.html

posted @ 2017-04-24 17:34  SapphireCastle  阅读(218)  评论(0编辑  收藏  举报