文章所有来自公众号:爱写bugjava
算法是一个程序的灵魂。 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.算法
给定长度为 2n 的数组, 你的任务是将这些数分红 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。数组
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).
Note:性能
提示:ui
其实就是把 数组排序,而后按顺序 每两个数既是一对,每对的第一个数累加之和即为所求。就是考一下各种排序算法的性能。code
先使用内置 sort()
函数理解一下思路:blog
Java:排序
import java.util.Arrays; class Solution { public int arrayPairSum(int[] nums) { Arrays.sort(nums); int sum=0; for (int i=0;i<nums.length;i+=2){ sum+=nums[i]; } return sum; } }
扩展:递归
维基百科上对排序算法介绍的很是详细,而且进行了归类比较,地址: https://zh.wikipedia.org/wiki/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95
这里简单推荐两个:
qsort()
排序用的就是快速排序算法,利用递归和分而治之思想)冒泡排序、选择排序都是比较简单容易理解,复杂度是 n^2
,因此再也不赘述。