Original title link
Expansion topic-the closest sum of three numbers
Extended question two-the sum of four numbers is a specific value
Title description
给出一个有n个元素的数组S,S中是否有元素a,b,c满足a+b+c=0?找出数组S中所有满足条件的三元组。
注意:
1.三元组(a、b、c)中的元素必须按非降序排列。(即a≤b≤c)
2.解集中不能包含重复的三元组。
Example
输入:
[-2,0,1,1,2]
输出:
[[-2,0,2],[-2,1,1]]
Reference solution
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
Arrays.sort(num);
ArrayList<Integer> r;
for (int i = 0; i < num.length; i++) {
// 过滤掉相同的左侧的值
if (i >= 1 && num[i] == num[i - 1])
continue;
for (int j = i + 1; j < num.length; j++) {
// 过滤掉相同的中间的值
if (j >= i + 2 && num[j] == num[j - 1])
continue;
int rest = -(num[i] + num[j]);
int index = Arrays.binarySearch(num, j + 1, num.length, rest);
// 查找到会返回一个大于等于0的值
if (index >= 0) {
r = new ArrayList<>();
r.add(num[i]);
r.add(num[j]);
r.add(num[index]);
res.add(r);
}
}
}
return res;
}
}
to sum up
This topic is mainly about learning how to deal with it 三个数的关系
and using it 一重循环+双指针
instead 三重循环
.