leedcode来一道随机简单题,写出题目标题,题目描述和思路,在代码块中用Java和Python解答
题目标题:数组拆分 I
题目描述:
给定长度为 2n 的数组 nums,你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。
思路:
将数组排序,然后将相邻的两个数组成一对,取每一对中的最小值,累加即为所求的最大总和。
Java代码:
class Solution { public int arrayPairSum(int[] nums) { Arrays.sort(nums); int sum = 0; for (int i = 0; i < nums.length; i += 2) { sum += nums[i]; } return sum; } }
Python代码:
class Solution: def arrayPairSum(self, nums: List[int]) -> int: nums.sort() res = 0 for i in range(0, len(nums), 2): res += nums[i] return res
原文地址: https://www.cveoy.top/t/topic/AjR 著作权归作者所有。请勿转载和采集!