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

  • 相关阅读:
    LeetCode
    LeetCode
    ELK系列(5)
    ELK系列(4)
    ELK系列(3)
    ELK系列(2)
    ELK系列(1)
    计算机网络常见面试题总结
    mosquitto启动时Address already in use 和 一般的 Address already in use
    size和STL中的size_type
  • 原文地址:https://www.cnblogs.com/SapphireCastle/p/6758013.html
Copyright © 2011-2022 走看看