dmndxld

码不停题

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.

 

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

 

My idea:use sort() and sum them which are 2n

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        nums.sort()
        max=0
        i=0
        while(i!=len(nums)):
            max+=nums[i]
            i=i+2
        return max

 

执行用时 : 148 ms, 在Array Partition I的Python3提交中击败了47.72% 的用户
内存消耗 : 15 MB, 在Array Partition I的Python3提交中击败了59.69% 的用户
 
learn about for 
class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        nums.sort()
        sum=0
        for i in nums[::2]:
            sum+=i
        return sum
执行用时 : 140 ms, 在Array Partition I的Python3提交中击败了59.97% 的用户
内存消耗 : 14.9 MB, 在Array Partition I的Python3提交中击败了87.38% 的用户
 
this one is better
 
not anything should use range() in for

posted on 2019-05-06 20:52  imyourterminal  阅读(111)  评论(0编辑  收藏  举报

导航