LeetCode刷题实战561数组拆分I
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 数组拆分 I,我们先来看题面:
https://leetcode-cn.com/problems/array-partition-i/
Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.
给定长度为 2n 的整数数组 nums ,你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从 1 到 n 的 min(ai, bi) 总和最大。
返回该 最大总和 。
示例 示例 1:
输入:nums = [1,4,3,2]
输出:4
解释:所有可能的分法(忽略元素顺序)为:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
所以最大总和为 4
示例 2:
输入:nums = [6,2,6,5,1,2]
输出:9
解释:最优的分法为 (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9
解题
由于数组的元素范围已经确定, 可以用一个临时数组当作 map存储出现的数字及个数
采取基数排序的思想
只需要取排序后的位于奇数位置上的元素和即可
时间复杂度O(n), 空间复杂度O(1)class Solution {
public int arrayPairSum(int[] nums) {
int count = new int[20001];
int index = 1, result = 0;
for (int i : nums) count[i + 10000]++;
for (int i = 0; i < 20001;) {
if (count[i] != 0) {
if ((index & 1) != 0) result += i - 10000;
index++;
count[i]--;
} else i++;
}
return result;
}
}
在看或者转发吧,你们的支持是我最大的动力 。
上期推文:
LeetCode1-560题汇总,希望对你有点帮助!