leetcode.561.Array Partition I

来源:互联网 发布:mac打开finder快捷键 编辑:程序博客网 时间:2024/06/14 00:04

Description

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

Note:
n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000].

sln1

当我们从数组中拿出a和b组成一个pair的时候,b将被抛弃(对最后的结果没有贡献)。也就是对于每个pair中的a而言,都有一个大于它的b会被抛弃。那么我们希望最后所有pair的a之和最大,那么我们在确定a的情况下要选择b时,我们会尽量选择一个和a尽量相近的b,那么抛弃掉b则不会对整个结果造成很大的损失。因此抱着这样naive的想法,我们只要对数组排个序,然后按顺序每两个数作为一个pair即可。这种方法的复杂度就是排序算法的复杂度,如果我们直接用c++标准库提供的排序函数,那么复杂度为O(nlogn)。该方法c++实现如下:

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

sln2

感觉上面的方法太naive了于是开始寻找discussion中大神的解法,看到一个用C++实现的O(n)复杂度的解法,大概看了下,其实思想还是一样,就是在确定pair中a的情况下,找到一个b使得b是剩余数中最接近a的。只是他的方法是用hashtable来实现,因为题目已经给出了所有数字的范围,所以可以不用排序。该方法c++实现如下:

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