题目:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
Java
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//返回结果创建
List<List<Integer>> res = new LinkedList<>();
if(nums.length <3)
return res;
//先对数组进行冒泡排序
maopao(nums);
//外层for循环,得到的是index
for (int i=0; i<nums.length&&nums[i]<=0; i++){
//如果当前值和上一个相等,直接跳过
if(i-1>=0&&nums[i]==nums[i-1]){
continue;
}
//index是值
int index=nums[i];
//内部循环,start和nums是坐标
for(int start = i + 1,end = nums.length-1; start<end;){
//如果三数之和大于0,end左移
if(index+nums[start]+nums[end]>0){
end--;
}
//如果三数之和小于0,start右移
else if(index+nums[start]+nums[end]<0){
start++;
}
//等于0时,给结果集增加新值
else{
List<Integer> list = new LinkedList<>();
list.add(index);
list.add(nums[start]);
list.add(nums[end]);
res.add(list);
//给start移一个新位置
for(;start<=end&&index+nums[start]+nums[end]==0;start++);
}
}
}
return res;
}
public void maopao(int[] nums){
int time = 1;
while (time!=0){
time = 0;
for(int i = 0; i < nums.length-1; i++){
if(nums[i]>nums[i+1]){
int a = nums[i+1];
nums[i+1] = nums[i];
nums[i] = a;
time++;
}
}
}
}
}