Leetcode学习(3)—— Array Partition I

来源:互联网 发布:购买淘宝店铺价格 编辑:程序博客网 时间:2024/05/16 06:43

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: 4Explanation: n is 2, and the maximum sum of pairs is 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].

思路:将整个数组升序排列,从下标为 0 处开始,每隔两个 取一个,并求和

class Solution(object):    def arrayPartitionI(self, nums):        return sum(sorted(nums)[::2])
0 0
原创粉丝点击