前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-561-Array Partition I

leetcode-561-Array Partition I

作者头像
chenjx85
发布2018-05-22 16:29:38
4740
发布2018-05-22 16:29:38
举报

题目描述:

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:

代码语言:javascript
复制
Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 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].

要完成的函数:

int arrayPairSum(vector<int>& nums) 

说明:

1、给定一个vector,里面包含2n个元素,要把这些元素组成n个对子,比如[1,3,2,4],可以组成[1,2],[3,4]这样的对子。

求每个对子的最小值,然后把最小值加起来求和,要让和最大,应该怎样组对子?能够输出最大的和是多少?

2、我们思考一下,比如[1,3,2,4]这样的vector,4这个最大值能不能作为和的一部分,明显不能,无论4跟谁搭配,都不能输出。

那3这个第二大的数呢?3只能跟4在一起的时候,才能输出。

那2呢?假如2跟4搭配,3跟1搭配,那么的确可以输出2,但是3就输出不了了。为了一个2,失去一个3,明显不值得。

所以最理想的搭配是[3,4]输出3,[1,2]输出1,我们要尽可能让大的数体现它的价值。

3、思路很清晰,代码如下:

代码语言:javascript
复制
    int arrayPairSum(vector<int>& nums) 
    {
        sort(nums.begin(),nums.end());//升序排列
        int s1=nums.size(),sum=0;
        for(int i=0;i<s1;i+=2)
            sum+=nums[i];
        return sum;
    }

代码简洁,实测76ms,beats 78.50% of cpp submissions。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档