Leetcode 561.Array Partition I
来源:互联网 发布:ubuntu 16.04 编辑:程序博客网 时间:2024/06/08 16:07
561.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.
Input: [1,4,3,2]Output: 4Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
Solution
//题面意思即 将2n个数分成n个二元组,并将每个二元组的小值累加,使得最后累加的结果最大//解题方式很容易,将数组排序,12分组,34分组,每次取第一个相加//理解方式多种多样,说一个比较形象一点的吧,如果有歧义或是有更好的解释方法,请指出哦,谢谢~共同进步//①每一个二元组,可以这么理解,较小数消灭了另一个(使得它等效于不存在)②当前需要分组的数组中最小的数必须被累加③我们需要做的是,累加这个最小数的同时,消灭一个最需要消灭的数,也就是下一个最小的数。 因此,可以这么做。 代码如下:class Solution {public: int arrayPairSum(vector<int>& nums) { sort(nums.begin(),nums.end()); //sort int ans = 0; for (int i = 0;i < nums.size();i += 2) ans += nums[i]; //get min value and add up return ans; }};
阅读全文
0 0
- LeetCode 561. Array Partition I
- LeetCode 561. Array Partition I
- [LeetCode]561. Array Partition I
- leetcode 561. Array Partition I
- LeetCode 561. Array Partition I
- Leetcode 561. Array Partition I
- [leetcode]561. Array Partition I
- LeetCode 561. Array Partition I
- LeetCode: 561. Array Partition I
- LeetCode 561. Array Partition I
- LeetCode: 561. Array Partition I
- LeetCode 561. Array Partition I
- LeetCode ** 561. Array Partition I
- leetcode.561.Array Partition I
- 【leetcode】561. Array Partition I
- [LeetCode]561.Array Partition I
- [leetcode]561. Array Partition I
- Leetcode 561.Array Partition I
- Kotlin-33.异常(Exception)
- C++String深浅拷贝
- 项目中使用Bootstrap以及基于bootstrap的 Bootgrid
- fatal: unable to access 'url': Failed connect to githup.com:443; No error
- 523. Continuous Subarray Sum
- Leetcode 561.Array Partition I
- IAR STM32 函数和变量的绝对地址定位
- 区别
- webstorm常用快捷键
- 湖南省第十二届大学生计算机程序设计竞赛 Parenthesis
- java字符串基础
- 状态模式——详解红绿灯问题
- POJ 1015--Jury Compromise
- 关注国情民情,从身边做起