美文网首页
561. Array Partition I 数组划分1

561. Array Partition I 数组划分1

作者: 这就是一个随意的名字 | 来源:发表于2017-07-30 09:51 被阅读0次

    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.
    给定含2n个元素的数组,将其分为n个二元组,使得每个二元组内较小的值的总和最小.

    Example 1:
    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].


    思路
    排序数组后将相邻元素划分为一组,取其中较小的,实际上就是偶数位的元素。
    不过本题只要求算法返回最小的和,可理解位2n个元素中取n个使得总和最小,可直接排序后输出前n个和即可。

    class Solution {
    public:
        int arrayPairSum(vector<int>& nums) {
            int res=0;
            sort(nums.begin(),nums.end());
            for(int i=0;i<nums.size();i+=2){
                res+=nums[i];
            }
            return res;
        }
    };
    

    相关文章

      网友评论

          本文标题:561. Array Partition I 数组划分1

          本文链接:https://www.haomeiwen.com/subject/ecuhlxtx.html