1.题目描述
2.思路和知识点
(1)这种题型出现很多次了,大概就是[1,2,3,4],要求元素之间两两配对比如(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)
import java.util.*;
class Solution {
public List<List<Integer>> pairCombination(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
// 遍历数组中的每个元素
for (int i = 0; i < nums.length - 1; i++) {
// 从当前元素的下一个位置开始遍历
for (int j = i + 1; j < nums.length; j++) {
// 构造当前配对的列表
List<Integer> pair = new ArrayList<>();
pair.add(nums[i]);
pair.add(nums[j]);
// 将当前配对添加到结果列表中
result.add(pair);
}
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 3, 4};
List<List<Integer>> pairs = solution.pairCombination(nums);
for (List<Integer> pair : pairs) {
System.out.println(pair);
}
}
}
[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]
(2)循环中的 i += 2 让变量 i 每次都增加 2,这是因为我们每次需要取相邻的两个数作为一对。通过每次增加 2,我们可以确保每次迭代都处理数组中的相邻两个数,并且不会重复处理同一个数。
(3)我们需要将数组中的数字分成尽可能多的对,并且使得每对中较小的数字之和最大化。因此,我们需要对数组进行排序,并且每次取相邻的两个数作为一对。
假设我们有一个数组 nums = [1, 2, 3, 4, 5, 6]。
1)排序数组
我们首先对数组进行排序,从小到大排列,得到 [1, 2, 3, 4, 5, 6]。
2)遍历数组并计算最小值之和
接下来,我们遍历排序后的数组,每次取相邻的两个数作为一对,并将每对中较小的数字之和累加起来。
第一对:(1, 2),最小值是 1。
第二对:(3, 4),最小值是 3。
第三对:(5, 6),最小值是 5。
3)将最小值相加得到 1 + 3 + 5 = 9。
3.代码实现
class Solution {
public int arrayPairSum(int[] nums) {
int sum=0;
Arrays.sort(nums);
for(int i=0;i<nums.length;i+=2)
{
sum=sum+nums[i];
}
return sum;
}
}