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

【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,所以小一些最小。

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

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值