Array Partition I

来源:互联网 发布:淘宝店铺线下推广方案 编辑:程序博客网 时间:2024/06/13 13:29

Array Partition I
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).
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].
总体思路:对向量中元素排序并输出每两个中的较小值的和

#include<iostream>#include<vector>using namespace std;class Solution {public:    int arrayPairSum(vector<int>& nums) {        int k,i,temp,s=0;        for (k = 0; k<nums.size(); k++)            for (i = k; i<nums.size(); i++)                if (nums[i]<nums[k]) //这里改为>,即可实现从大到小排列                {                    temp = nums[i];                    nums[i] = nums[k];                    nums[k] = temp;                }        for (size_t i = 0; i < nums.size(); i = i + 2)        {            s = s + nums[i];        }        cout << s << endl;        return s;    }};int main(){    Solution n;    vector<int> s ;//向量元素的输入都要依次输入,后续可以改变    s.push_back(1);    s.push_back(4);    s.push_back(3);    s.push_back(2);    s.push_back(5);    s.push_back(6);    n.arrayPairSum(s);}

总结:
题目比较简单,复习排序算法以及vector的使用、思路想法

原创粉丝点击