美文网首页
561. Array Partition I

561. Array Partition I

作者: oneSophia | 来源:发表于2018-11-30 13:48 被阅读0次

地址:
https://leetcode.com/problems/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: 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].

题目思路

  • 两两分组,找出每组最小值加起来最大的解决方案,如果一大一小两个一组,大的就浪费了,所以按照大小排序,相邻的一组,故加起来是偶数序号的数字之和
  • 解题关键是数组排序,我自己的做法是用的java自己的Arrays.sort()方法

解法1(自己的解法)

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

26 ms, faster than 53.83%

解法2

public class Solution {
    public int arrayPairSum(int[] nums) {
        int[] exist = new int[20001];
        for (int i = 0; i < nums.length; i++) {
            exist[nums[i] + 10000]++;
        }
        int sum = 0;
        boolean odd = true;
        for (int i = 0; i < exist.length; i++) {
            while (exist[i] > 0) {
                if (odd) {
                    sum += i - 10000;
                }
                odd = !odd;
                exist[i]--;
            }
        }
        return sum;
    }
}

这个 O(n) beats 100%确实厉害,运用了桶排序的思路。
接下来学习排序算法。

相关文章

网友评论

      本文标题:561. Array Partition I

      本文链接:https://www.haomeiwen.com/subject/brqhcqtx.html