561. Array Partition I

来源:互联网 发布:淘宝自动纸箱封箱机 编辑:程序博客网 时间:2024/06/05 04:22

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:

Input: [1,4,3,2]Output: 4Explanation: n is 2, and the maximum sum of pairs is 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].

翻译

给定一个2n个整数的数组,你的任务是将这些整数分成n对整数,例如(a 1,b 1),(a 2,b 2),…,(a n,b n)所有i从1到n 的最小(a i,b i)的和尽可能大。

示例1:
输入: [1,4,3,2]

输出: 4
说明: n为2,最大对的总和为4。
注意:
n是正整数,在[1,10000]的范围内。
数组中的所有整数将在[-10000,10000]的范围内。

解题思路

public 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;    }}

其中有一个使用桶排序的方法速度非常的快,借此机会又好好学习了一下桶排序,根据原理具体代码如下

public class Solution {    public int arrayPairSum(int[] nums) {        if(nums == null || nums.length == 0) return 0;        int sum = 0, carry = 0;        int[] map = new int[20001];        for(int i : nums) map[i + 10000]++;        for(int i = 0; i < map.length; i++) {            if(map[i] == 0) continue;            sum += (map[i] - carry + 1) / 2 * (i - 10000);            carry = (map[i] - carry) % 2;        }        return sum;    }}

欢迎加入中科院开源软件自习室:631696396

欢迎加入中科院开源软件自习室
http://70b86a48.wiz03.com/share/s/1MK6F81-vQ1i2DFlsT0ux-iU2hthmp19lQ1Z2bi8om3TEC1I

原创粉丝点击