LeetCode-Easy-Java——Array Partition I
来源:互联网 发布:淘宝一口价设置技巧 编辑:程序博客网 时间:2024/05/29 19:04
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: 4Explanation: 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].
题目要求:给定一个包含2n个整数的数组,把这2n个数分成n对,每对数可以表示为(a1, b1), (a2, b2), ..., (an, bn) ,要求使这n对数中每对数的最小值的和最大。有点绕,看例子还比较容易理解,如果有疑问可以评论留言呐。
解决思路:我觉得算是利用贪心算法的一种。为了让最后的和(sum)最大,所以肯定希望较大值都被加进来。我们先对数组进行一个排序,变为递增序列[a0, a1, a2, a3, ..., a2n-1],其中a2n-1是最大值,a0是最小值。为了能让和(sum)最大,最先考虑的是a2n-2(因为a2n-1是最大值,没有数能与它构成一对,使它加到sum中),为了让a2n-2加到sum中,则需要让它和a2n-1组成一对;下一个考虑的就是a2n-4,同理为了让a2n-4加进来,就让它与a2n-3组成一对。因为每次加进来都是剩余数组中的最大值,所以最后的和(sum)也是最大的。
代码如下:
class Solution { public int arrayPairSum(int[] nums) { int sum=0; Arrays.sort(nums); for(int i=0;i<nums.length/2;i++){ sum+=nums[2*i]; } return sum; }}
更多算法内容 关注 FunctionYcsdn博客
阅读全文
0 0
- LeetCode-Easy-Java——Array Partition I
- [easy]561. Array Partition I
- LeetCode Array Partition I
- leetCode---Array Partition I
- Array Partition I(leetcode)
- Leetcode-Array Partition I
- leetcode Array Partition I
- Leetcode学习(3)—— Array Partition I
- LeetCode——561. Array Partition I(贪心,C++)
- 【leetcode】Array——easy(java)
- leetcode array数组刷题easy组:561:Array Partition I
- 561. Array Partition I; Difficulty : Easy
- 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
- 提高代码阅读能力的7种方法
- 无标题Markdown(1)
- [BZOJ 3523] Bricks 贪心+优先队列/堆
- 022day(指针和数组和指向指针的指针)
- Android ListView组件的优化
- LeetCode-Easy-Java——Array Partition I
- 消息应答机制重复发送JMS(八)
- ZOJ 3993Safest Buildings (数学题)
- 日历命令 cal
- ch04_使用多个映射的例子
- 归并排序
- SetACL Studio [windows权限操作工具][翻译]
- PAT Basic 1004
- hdu 1222 Wolf and Rabbit(gcd)