zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    XSS 防御方法总结
    IE浏览器兼容方案
    js 排序算法
    webapck 打包体积优化策略
    webapck 速度优化策略
    Grunt、Gulp和Webpack对比
    数据库中的undo日志、redo日志
    使用sysbench对mysql压力测试
    java -cp & java jar的区别
    使用BenchmarkSQL测试PostgreSQL
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10822003.html
Copyright © 2011-2022 走看看