zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    hdu 5072 Coprime (容斥)
    洛谷 P1411 树 (树形dp)
    Tr/ee AtCoder
    sys.path
    uname
    sys.platform
    Eclipse Basic
    Eclipse Color Theme
    Pydev
    scons
  • 原文地址:https://www.cnblogs.com/SapphireCastle/p/6758013.html
Copyright © 2011-2022 走看看