561. Array Partition I
2017-05-02 20:35
381 查看
题目:给定一个序列有2n个数,目标是把它们分成n组,(ai,bi),使得ai和bi中较小的那个的所有的加和最大,输出这个值。
Example 1:
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].
思路:排序,将奇数位的数相加
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
int n=nums.size();
if(n%2) return 0;
int sum=0;
for(int i=0;i<n;i++)
{
sum+=nums[i];
i++;
}
return sum;
}
};
Example 1:
Input: [1,4,3,2] Output: 4 Explanation: 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].
思路:排序,将奇数位的数相加
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
int n=nums.size();
if(n%2) return 0;
int sum=0;
for(int i=0;i<n;i++)
{
sum+=nums[i];
i++;
}
return sum;
}
};
相关文章推荐
- 【LeetCode】561 Array Partition I
- LeetCode-561 Array Partition I
- 561. Array Partition I
- leetcode array数组刷题easy组:561:Array Partition I
- Leetcode算法学习日志-561 Array Partition I
- 561. Array Partition I
- 数组-leetcode 561 Array Partition I
- leetcode 561 Array Partition I
- 561. Array Partition I
- Leetcode 561 Array Partition I
- LeetCode-561-Array Partition I-E
- leetcode 561 Array Partition I
- 561. Array Partition I
- leetcode-561-Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- [leetcode 561]Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- 561. Array Partition I