108 - 561数组拆分

题目

给定长度为 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).

提示:

  1. n 是正整数,范围在 [1, 10000].

  2. 数组中的元素范围在 [-10000, 10000].

解答

想到的办法,就是排序,然后成对取最小的加起来

func arrayPairSum(nums []int) int {
    sort.Ints(nums)
    var ans int
    for i := 0; i < len(nums); i += 2 {
        ans += nums[i]
    }
    return ans
}

Runtime: 72 ms, faster than 79.70% of Go online submissions for Array Partition I.

Memory Usage: 6.8 MB, less than 100.00% of Go online submissions for Array Partition I.

Runtime: 144 ms, faster than 9.13% of JavaScript online submissions for Array Partition I.

Memory Usage: 39 MB, less than 55.56% of JavaScript online submissions for Array Partition I.

Runtime: 340 ms, faster than 44.26% of Python3 online submissions for Array Partition I.

Memory Usage: 16.5 MB, less than 6.06% of Python3 online submissions for Array Partition I.

看到大佬强悍的证明以及强行一行:

Runtime: 328 ms, faster than 81.53% of Python3 online submissions for Array Partition I.

Memory Usage: 16.3 MB, less than 6.06% of Python3 online submissions for Array Partition I.

Last updated

Was this helpful?