博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 561. Array Partition I (数组分隔之一)
阅读量:4330 次
发布时间:2019-06-06

本文共 1032 字,大约阅读时间需要 3 分钟。

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:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].

 


题目标签:Array

 

  这道题目给了我们一个数组有2n integers, 需要我们把这个数组分成n对,然后从每一对里面拿小的那个数字,把所有的加起来,返回这个sum。并且要使这个sum 尽量最大。如何让sum 最大化呢,我们想一下,如果是两个数字,一个很小,一个很大,这样的话,取一个小的数字,就浪费了那个大的数字。所以我们要使每一对的两个数字尽可能接近。我们先把nums sort 一下,让它从小到大排列,接着每次把index: 0, 2, 4...偶数位的数字加起来就可以了。
 
 

Java Solution:

Runtime beats 83.27% 

完成日期:05/10/2017

关键词:Array

关键点:Sort

1 public class Solution  2 { 3     public int arrayPairSum(int[] nums)  4     { 5         int sum = 0; 6          7         Arrays.sort(nums); 8          9         for(int i=0; i

参考资料:N/A

 

LeetCode 题目列表 - 

 

转载于:https://www.cnblogs.com/jimmycheng/p/7119306.html

你可能感兴趣的文章
influxDB的安装和简单使用
查看>>
JPA框架学习
查看>>
JPA、JTA、XA相关索引
查看>>
机器分配
查看>>
php opcode缓存
查看>>
springcloud之Feign、ribbon设置超时时间和重试机制的总结
查看>>
Go 结构体
查看>>
LINQ巩固
查看>>
观看杨老师(杨旭)Asp.Net Core MVC入门教程记录
查看>>
UIDynamic(物理仿真)
查看>>
Windows下安装Redis
查看>>
迷宫实现
查看>>
【字符编码】Java字符编码详细解答及问题探讨
查看>>
学习操作系统导图
查看>>
在线的JSON formate工具
查看>>
winform非常实用的程序退出方法!!!!!(转自博客园)
查看>>
xml解析
查看>>
centos安装vim
查看>>
linux工作调度(计划任务)
查看>>
hdu--1698 Just a Hook(线段树+区间更新+懒惰标记)
查看>>