您的位置:首页 > 其它

【Leetcode】561. Array Partition I(数组分割一)

2018-02-06 20:16 525 查看

【Leetcode】561. Array Partition I(数组分割一)

题目链接:https://leetcode.com/problems/array-partition-i/description/

问题描述:

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


解释:什么意思呢,就是长度为2n的数组分为n个长度为2的数组,然后取将每个数组中两个数的最小值,让n个数组的最小值之和最大,然后输出最大值的和。

注意:[1,4,3,2]

分组:①[1,2],[3,4] 1+3=4    (最大)

 ②[1,3],[2,4]
1+2=3

 ③[1,4],[2,3]
1+2=3

所以选择顺序排序,然后和最大。因为如果不顺序排序的话,如[1,3][2,4],[1,3]浪费了3,

[1,2]浪费了2,所以小一些最小。

引用 :“<
4000
em>每组数值越接近,浪费的数值越小,所得的总和最大”。

Java:

/*package leetCode;
import java.util.Arrays;*/
public class Solution {
//将数组排序,把所有下标为偶数的加和
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int count=0;
for(int i=0;i<nums.length;i+=2){
count+=nums[i];
}
return count;
}
}

C++:

/*#include <iostream>
#include <vector>
#include <algorithm> //调用sort()函数
using namespace std;*/
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int res = 0;
sort(nums.begin(), nums.end());
for(int i=0; i<nums.size(); i+=2){
res += nums[i];
}
return res;
}
};
/*int main()
{
Solution a;
int num[4] = {1, 4, 3, 2};
int numLength = sizeof(num) / sizeof(num[0]);
vector<int> nums(num, num+numLength);
cout << a.arrayPairSum(nums) << endl;
return 0;
}*/

日期:2018/2/6-20:09
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode