LeetCode 561. Array Partition I
来源:互联网 发布:哪些化妆品比较好知乎 编辑:程序博客网 时间:2024/06/05 03:37
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.
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].
Analysis
核心思想:容易知道,最佳方案是将数值上相邻的两个数字组为一个group,选每个group小的数字求和,即为最后答案。简单地反证可以验证这一思路。
那么差异就出现在实现方法上。
方法一:对这2n
个整数进行排序,排序后求和公式为
方法二:由于题目中给出了数字的范围,不太大,可以直接用哈希表来记录数字的出现次数,自然而然实现排序效果,但时间复杂度降到了
Code
class Solution {public: int arrayPairSum(vector<int>& nums) { int n = nums.size(); sort(nums.begin(),nums.end()); int sum = 0; for (int i = 0; i < n; i+=2){ sum += nums[i]; } return sum; }};
Appendix
- Link: https://leetcode.com/problems/array-partition-i/
- Run Time:
- Version 1: 83ms
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
- HashMap和Hashtable的区别
- easyui datagrid 根据关键字值取行以及idField的注意事项
- Http和Https的区别
- GC的三大基础算法
- Tensorflow入门学习网站以及资料<一>
- LeetCode 561. Array Partition I
- 注入攻击命令大全
- 面试算法题
- Servlet的转发和重定向的区别
- TCP/IP四层模型
- Effective C++,rule 1,View C++ as a federation of languages
- 消息中间件和JMS介绍(一)
- MyEclipse+Tomcat+MAVEN+SVN项目完整环境搭建
- QT关于qml的Component事件