Leetcode PHP题解--D14 561. Array Partition I
561. Array Partition I
题目链接
561. Array Partition I
题目分析
本题给了一个数组,要求将数组分为n个只有2个元素的一对。
使得每对数字中最小的数加起来的和最大。
思路
首先,需要把数组分为2个一对。用array_chunk
即可。
其次,需要取每对数字中最小的那一个数字,用于求和。
因为我们需要最终求和最大,但每组数字中又取最小。
因此,要使每组中最大的数字和最小的数组之差最小,这样才能使“损失”最小。
例如,[1,2,7,8]
。
若分为[[1,8],[2,7]]
或[[1,7],[2,8]]
两组,那么每组取最小后,会得到[1,2]
。求和后为3。
当比较大的数字和比较小的数字数字组成一对时,较大的数字都没办法用于求和(因为题目要取每组数字中最小的数)。
当分为[[1,2],[7,8]]
两组时,每组取最小后,会得到[1,7]
。求和后为8,比3大。
故,先对数组排序,再两两分组,从每组中获取第0个元素参与计算即可。
最终代码
<?php
class Solution {function arrayPairSum($nums) {sort($nums);$a = array_chunk($nums,2);return array_sum(array_column($a,0));}
}
复制代码
若觉得本文章对你有用,欢迎用爱发电资助。
Leetcode PHP题解--D14 561. Array Partition I相关推荐
- [LeetCode]561. Array Partition I (数组分区 1)
561. Array Partition I Given an array of 2n integers, your task is to group these integers into n pa ...
- Leetcode刷题记录[java]——561 Array Partition I
一.前言 二.题561 Array Partition I Given an array of 2n integers, your task is to group these integers in ...
- 561.Array Partition I--Python
刚开始学习Python编程,欢迎交流学习! 561.Array Partition I Given an array of 2n integers, your task is to group the ...
- 【刷leetcode,拿Offer-009】561. Array Partition I(贪心,C++)
题目链接 Given an array of 2n integers, your task is to group these integers into n pairs of integer, sa ...
- LeetCode 561. Array Partition I
题目: Given an array of 2n integers, your task is to group these integers into n pairs of integer, say ...
- LeetCode 561 Array Partition I(数组划分)
翻译 原文 Given an array of 2n integers, your task is to group these integers into n pairs of integer, s ...
- leetcode#561 Array Partition I
Description: Given an array of 2n integers, your task is to group these integers into n pairs of int ...
- 561. Array Partition I
原题 Given an array of 2n integers, your task is to group these integers into n pairs of integer, say ...
- 561. 数组拆分 I(javascript)561. Array Partition I
给定长度为 2n 的整数数组 nums ,你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), -, (an, bn) ,使得从 1 到 n 的 min(ai, bi) 总和 ...
最新文章
- 专为设计师而写的GitHub快速入门教程
- axios delete有请求体吗_封装 axios 取消重复请求
- python右对齐输出如果结果超过30个字符_Python3 输出字符串左对齐、右对齐、居中对齐...
- 你有一份云栖大会的IoT邀请函,请查收
- windows下搭建基于nginx的rtmp服务器
- PAT乙级(Basic Level)真题--跟奥巴马一起编程(15)
- zabbix mysql.status_zabbix 监控mysql状态
- 谈MicroMessageTest的开始创建
- Java并行计算线程池_干货!线程池+CountDownLatch,实现 多线程并发计算、汇总
- 兔子问题JAVA编程题
- Spark1.5.1学习笔记汇总
- Flutter 的ButtonBar
- ORL Face94 LFW
- 最有用的25个 Matplotlib图(含Python代码模板)
- 个人计算机软件著作权,个人可以申请软件专利权吗?软件著作权申请的注意事项有哪些?...
- 杭州电子科技大学java刷题_杭州电子科技大学的OJ
- 百度地图和百度导航冲突问题
- java wgs84 百度坐标_javascript 实现wgs84 坐标转百度坐标
- 如何用Excel做动态图表
- 提示用户输入一个高考_高考报名用户名密码显示错误怎么办