您的位置:首页 > 编程语言 > Python开发

leetcode array数组刷题easy组:561:Array Partition I

2017-08-27 09:53 651 查看
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: 4
Explanation: 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].

首先这个题其实很简单,但是因为我理解上出了偏差,导致我走错了路。给你一个2n的数组,然后让你把它分成n个包含两个数的数组,例如[1,4,5,6,7,8,3,18],可以分为4个包含两个数的数组,举例来说,其中一个分类:[1,4],[5,6],[7,8],[3,18]。然后程序的要求就是求出每个分组的最小值的和,最终得到的和是所有分组里面最大的。

分析:其实看到这个题目,想一想应该就能想到先把数组按从小到大排序,然后按照排序分组,从头开始。每一组取最小值,然后最终将各组最小值相加,即可求得最大的和。简而言之,排序分组,把序号为偶数的所有值相加,就是最后的结果。

方法一:runtime:49ms

class Solution(object):

    def arrayPairSum(self, nums):

        """

        :type nums: List[int]

        :rtype: int

        """

        nums.sort()

        return sum(nums[::2])

方法二:一行代码,runtime:29ms

class Solution(object):

    def arrayPairSum(self, nums):

        """

        :type nums: List[int]

        :rtype: int 

        """

    

        return sum(sorted(nums)[::2])

总结:这个题目,其实很简单,但是由于我看错了题目,看到题目中的示例,天真的写出了只能求出两个数组最小值的和的程序。被实例迷惑了。其实题目是求出所有分组的最小值的和。哈哈,也是对自己无语。还有这题目主要考的是数组的取值问题,在Python中,对应的就是序列分片求和。因为自己序列这方面基础知识基本上忘了,导致想不到怎么取到数组所有偶数序号的值。这就尴尬了啊,自己对编程语言基础知识还是掌握不牢,只能继续努力看了。再把Python中序列的知识拿出来看一遍了,只能这样了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息