描述
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.
Example1:
1 | Input: [1,4,3,2] |
Note:
1 | 1. n is a positive integer, which is in the range of [1, 10000]. |
分析
思考这种问题有几个方向,一个是多举几个例子,从中找出规律,然后写代码解决即可,另一种是直接用抽象思维解决,还有一种就是比较学院派,用数学证明。这里解释一下我的思考。先考虑极端的情况,如果配对的方式是最小的值和最大的值配对,倒数第 2 小和倒数第 2 大的值配置… 想象这些值从左至右从小到大排序,那么我们拿到的就是左边那一半的数字的和,我们得到的结果就是所能获得的总数的最小值,题目要求是总数最大,那么选择的这些数字应该尽可能地向右边靠拢,最理想的情况就是相邻的数字进行比较,总数是第 2 大,第 4 大,第 6 大… 的值进行相加。所以说解决方案就是,先将数组进行排序,取第 0 个,第 2 个,第 4 个…直到第 2n-1 个即可。
讨论里有一个数学证明:https://discuss.leetcode.com/topic/87206/java-solution-sorting-and-rough-proof-of-algorithm/2
解决方案1(Java)
1 | public class Solution { |
解决方案2(Python)
1 | class Solution(object): |
解决方案3(Golang)
1 | func arrayPairSum(nums []int) int { |