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的使用、思路想法
阅读全文
0 0
- Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- Array Partition I
- LeetCode Array Partition I
- 561. Array Partition I
- Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- leetCode---Array Partition I
- 561. Array Partition I
- JAVA多线程执行cmd命令
- 【Linux】中TCP的四大定时器
- [NOIP2017模拟]流
- TLD算法的相关研究(1)
- 软件测试基本分类
- Array Partition I
- Android Parcelable数据异常(问题)
- angularjs学习总结 详细教程
- git 简单操作
- mysql的内存表
- 未来币-概念介绍-资产、货币、代币
- 深入了解yii2框架
- 利用分类模型学习特征权重
- cmd命令,越爱越喜欢计算机了...