「数组拆分」| leetcode 刷题012

版权声明:转载请注明出处 https://blog.csdn.net/sixkery/article/details/82287692

题目

给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), …, (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。

示例 1:

输入: [1,4,3,2]

输出: 4
解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4).
提示:

  • n 是正整数,范围在 [1, 10000].
  • 数组中的元素范围在 [-10000, 10000].

解答

列表排序求奇数和

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        num = sorted(nums)
        count = 0
        for i in range(0,len(num),2):
            count = count + num[i]
        return count

再看看一行代码搞定的:

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

脑回路真是清奇。

猜你喜欢

转载自blog.csdn.net/sixkery/article/details/82287692