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;
        }
    };
  • 相关阅读:
    openstack 网络架构 nova-network + neutron
    编程算法
    16周(项目四 动态数组)
    iptables惹的祸
    【剑指offer】和为定值的连续正数序列
    root用户改动普通用户文件
    Android学习四、Android中的Adapter
    初探swift语言的学习笔记四(类对象,函数)
    crtmpserver 基本流程分析
    八大排序算法总结
  • 原文地址:https://www.cnblogs.com/silentteller/p/10708404.html
Copyright © 2011-2022 走看看