解法一 暴力
三层循环,遍历所有的情况。但需要注意的是,我们需要把重复的情况去除掉,就是 [1, -1 ,0] 和 [0, -1, 1] 是属于同⼀种情况的。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(int i=0; i<nums.length; i++){
for(int j=i+1; j<nums.length; j++){
for(int k=j+1; k<nums.length; k++){
if(nums[i] + nums[j] + nums[k] == 0){
List<Integer> temp = new ArrayList<Integer>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
//判断结果中是否已经有 temp
if(isInList(res, temp)){
continue;
}
res.add(temp);
}
}
}
}
return res;
}
public boolean isInList(List<List<Integer>> r, List<Integer> t){
for(int i=0; i<r.size(); i++){
//判断两个 List 是否相同
if(isSame(r.get(i), t)){
return true;
}
}
return false;
}
public boolean isSame(List<Integer> a, List<Integer> b){
int count;
Collections.sort(a);
Collections.sort(b);
//排序后判断每个元素是否对应相等
for(int i=0; i<a.size(); i++){
if(a.get(i) != b.get(i)){
return false;
}
}
return true;
}
}
解法二
主要思想是,遍历数组,⽤ 0 减去当前的数,作为 sum ,然后再找两个数使得和为 sum。
最最优美的地⽅就是,⾸先将给定的 num 排序。
这样我们就可以⽤两个指针,⼀个指向头,⼀个指向尾,去找这两个数字,这样的话,找另外两个数时间复杂度就会从 O(n²),降到 O(n)。
而要保证不加入重复的 list,我们的 nums 已经有序了,所以只需要找到⼀组之后,当前指针要移到和当前元素不同的地⽅。其次在遍历数组的时候,如果和上个数字相同,也要继续后移。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new LinkedList<>();
for(int i=0; i<nums.length-2; i++){
if(i == 0 || (i > 0 && nums[i] != nums[i-1])){
int l = i + 1, h = nums.length - 1, sum = 0 - nums[i];
while(l < h){
if(nums[l] + nums[h] == sum){
res.add(Arrays.asList(nums[i], nums[l], nums[h]));
while(l < h && nums[l] == nums[l+1]) l++;
while(l < h && nums[h] == nums[h-1]) h--;
l++; h--;
}else if(nums[l] + nums[h] < sum){
l++;
}else{
h--;
}
}
}
}
return res;
}
}