All articles from the public number: Write love bug
算法是一个程序的灵魂。
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.
A given length of 2n array, your task is divided into the number of these n pairs, such as (a1, b1), (a2 , b2), ..., (an, bn), such that from 1 to n min ( ai, bi) the sum of the maximum.
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:
- n is a positive integer, which is in the range of [1, 10000].
- All the integers in the array will be in the range of [-10000, 10000].
prompt:
- n is a positive integer in the range [1, 10000].
- Range of elements in the array [-10000, 10000].
Problem-solving ideas:
In fact, the array is sorted, and then sequentially each of the two numbers is both a pair, each pair of the first number and the accumulated sum is also desired. It is about to test the performance of various types of sorting algorithms.
First use the built-in sort()
function to understand some ideas:
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;
}
}
Extended:
Wiki encyclopedia of sorting algorithms described in great detail, and are classified compared address: https://zh.wikipedia.org/wiki/%E6%8E%92%E5%BA%8F%E7%AE%97 % E6% B3% 95
Here two simple recommendation:
- Quick sort (quick sort) - the expected time, the worst case; for large, random number list is generally believed to be the fastest known sorting (C language standard library
qsort()
for sorting is quick sort algorithm, recursive thinking and divide and rule) - Bucket sort (the Sort bucket) - ; require additional space (typical sacrifice space for time)
Bubble sort, selection sort are relatively simple and easy to understand the complexity of Shi n^2
, so will not repeat them.