【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] Array Partition I 数组分割之一
- [LeetCode]561. Array Partition I (数组分区 1)
- 数组-leetcode 561 Array Partition I
- leetcode -- 561. Array Partition I 【贪心算法 + 正确性证明】
- leetcode 561. Array Partition I(C语言)10
- LeetCode 561. Array Partition I (数组分隔之一)
- leetcode array数组刷题easy组:561:Array Partition I
- [LeetCode] 548. Split Array with Equal Sum 分割数组成和相同的子数组
- LeetCode 分割整数数组,分割为两部分的和相等
- [LeetCode] Split Array Largest Sum 分割数组的最大值
- [LeetCode] Split Array into Consecutive Subsequences 将数组分割成连续子序列
- [LeetCode] Split Array with Equal Sum 分割数组成和相同的子数组
- [LeetCode] Partition Equal Subset Sum 相同子集和分割
- LeetCode 548. Split Array with Equal Sum (分割数组使得子数组的和都相同)$
- Leetcode 410. 分割数组的最大值
- lintcode 容易题:Partition Array by Odd and Even 奇偶分割数组
- LeetCode 561. Array Partition I
- leetcode_561. Array Partition I ? 待解决
- Leetcode 561. Array Partition I(Easy)
- [Leetcode] 561. Array Partition I 解题报告