561.Array Partition I - LeetCode

?题目描述

给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。

示例 1:

输入: [1,4,3,2]

输出: 4
解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4).
提示:

n 是正整数,范围在 [1, 10000].
数组中的元素范围在 [-10000, 10000].

 ?Method 1: 正常操作

//O(nlogn)
class Solution {
public:
    int arrayPairSum(vector<int>& nums) {
        int n = nums.size(), ans = 0;
        if (n % 2 != 0) return 0;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); i += 2) {
            ans += min(nums[i], nums[i + 1]);
        }
        return ans;
    }
};

 ?Method 2: 计数排序,用空间换时间,避免了排序时间,从O(nlogn)降到O(n)

class Solution {
public:
    int arrayPairSum(vector<int>& nums) {
        const int MaxValue = 10000;
        array<int, 2 * MaxValue+1> count{};
        //count数组size是数字区间的两倍,用来存放一个数字出现的个数,初始置为0
        for (int num:nums) ++count[num+MaxValue];
        int ans = 0;
        bool first = true;
        int n = 0; // n属于(-10000,10000)
        while(n<count.size()){
            if (!count[n]) { ++n;continue;} // 如果没有n在测试数组中出现过,就判断下一个
            if (first) {
                ans += (n-MaxValue);
                first = false;
            } else {first = true;}
            --count[n];
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值