zoukankan      html  css  js  c++  java
  • 算法--leetcode 561. Array Partition I

    题目:

    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.

    题意:

    给出一个长度为2n的数组,将他们两个一组,分为n组,求每一组中的较小值,求这些较小值相加的最大和。

    输入输入样例:

    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].

    Python 解:

    思路:使用自带函数sorted排序,将索引为0,2,4,6....n-2的数相加(即奇数顺序的数),时间复杂度为nlog(n)

    class Solution(object):
        def arrayPairSum(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            return sum(sorted(nums)[::2])
            

    C++解:

    思路:时间复杂度为 O(n),说是哈希,但其实是桶排序,桶排序和哈希排序主要思想都差不多,使用flag 跳过偶数 只相加奇数,因为有负数所以+10000

    用空间换时间,

    语法要点:使用了vector容器,vector<int>& nums直接将 nums 数组赋值给vector容器。

    vector意为向量,可以理解为数组的增强版,封装了许多对自身操作的函数。

    class Solution {
    public:
        int arrayPairSum(vector<int>& nums) {
            int ret = 0;
            bool flag = true;
            array<int, 20001> hashtable{ 0 };
            for (const auto n : nums) {
                ++hashtable[n + 10000];
            }
            for (int i = 0; i < 20001;) {
                if (hashtable[i] > 0) {
                    if (flag) {
                        flag = false;
                        ret += (i - 10000);
                        --hashtable[i];
                    } else  {
                        flag = true;
                        --hashtable[i];
                    }
                } else
                    ++i;
            }
            return ret;
        }
    };

     

  • 相关阅读:
    AntSword 中国蚁剑的下载安装配置(附下载文件)
    开园第一笔
    四舍五入小技巧
    PAT B# 1025 反转链表
    WebService如何根据对方提供的xml生成对象
    解决Web部署 svg/woff/woff2字体 404错误
    解决TryUpdateModel对象为空的问题
    IIS集成模式下,URL重写后获取不到Session值
    SQLServer清空数据库中所有的表并且ID自动归0
    win2003 64位系统IIS6.0 32位与64位间切换
  • 原文地址:https://www.cnblogs.com/derek-dhw/p/8074678.html
Copyright © 2011-2022 走看看