LeetCode

来源:互联网 发布:天津seo平台 编辑:程序博客网 时间:2024/06/07 19:41

题目

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).

没看懂什么意思。

思路

  将数组排序,再隔一个数取值相加即可。

代码

    public int arrayPairSum(int[] nums) {        int res = 0;        // 输入数据合法性判断        if (nums == null || nums.length % 2 == 1) {            return -1;        } else if (nums.length == 0) {            return res;        }        Arrays.sort(nums);        for (int i = 0; i < nums.length; i += 2) {            res += nums[i];        }        return res;    }