zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    tcpdump命令
    浅谈  curl命令
    MongoDB下rs.status()命令
    Device mapper存储方式
    top命令
    cat命令汇总整理
    centos7搭建nginx日志
    CentOS7 防火墙(firewall)的操作命令(转)
    服务器的硬件组成
    shell随机生成10个文件
  • 原文地址:https://www.cnblogs.com/silentteller/p/10708404.html
Copyright © 2011-2022 走看看