561. Array Partition I

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.

Example 1:

1
2
3
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:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].

题目大意:

给定一个长度为2n(偶数)的数组,分成n个小组,返回每组中较小值的和sum,使sum尽量大

思路:

先将数组从大到小进行排列,将相邻两个数分为一组,每组较小数都在左边,求和即可。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package cn.caoler.Array.No561;

import java.util.Arrays;

/**
* Author: Caole
* CreateDateTime: 2017/10/11 15:46
* Description:
*/
public class main {
public static int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int sum = 0;
for (int i = 0; i < nums.length; i += 2) {
sum += nums[i];
}
return sum;
}
public static void main(String[] args) {
int[] num = {1,2,3,4,5,6,7,8};
System.out.println(arrayPairSum(num));
}
}

其中使用了Arrays.sort()函数,其功能参照API文档如下:

1
static void sort(byte[] a)  按照数字顺序排列指定的数组。

且 for循环时直接使用 i += 2 提升效率。

0%