LeetCode 561. Array Partition I (C++)

题目:

Given an array of 2n integers, your task is to group these integers into npairs 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 = 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].

分析1:

给定一个大小为2n数组,其内元素两两一组,组内求min,总体求max值。

很明显,我们希望每一组内的两个元素尽可能的相近,这样在求min之后的和一定是最大的。所以可以进行排序,然后直接对0,2,4,...加和处理。

程序1:

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

分析2:

看到一种O(n)的解法。使用桶排序,因为note中给定了元素的范围是[-10000,10000],我们可以开辟一个20001大小的数组,将元素的值和数组的索引联系起来,-10000存在n[0]中,10000存在n[20000]中,在按照索引大小对数组进行遍历,通过设定flag的值来交替将数组中的值加到sum中,以起到求两数较小值的功能。不过这种方法牺牲了空间,属于用空间来换时间的做法。

程序2:

class Solution {
public:
    int arrayPairSum(vector<int>& nums) {
        vector<int> n(20001, 0);
        for(int i:nums)
            n[i+10000]++;
        int flag = 1;
        int sum = 0;
        for(int i = 0; i < 20001;){
            if((n[i] > 0)&& flag == 1){
                sum += (i-10000);
                n[i]--;
                flag = 0;
            }
            else if((n[i] > 0) && flag == 0){
                n[i]--;
                flag = 1;
            }
            else
                i++;
        }
        return sum;
    }
};

转载于:https://www.cnblogs.com/silentteller/p/10708404.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值