一、三数之和
- 给定一个整数数组nums,判断是否存在[nums[i],nums[j],nums[k]]满足i != j、i != k且j != k,同时还满足nums[i] + nums[j] + nums[k] == 0.请你返回所有和为0且不重复的三元组
eg:输入:[-1,0,1,2,-1,-4]
输出:[[-1,0,1],[-1,-1,2]]
二、暴力解法
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class VoliceSolution {
public static List<List<Integer>> threenum(int[] nums){
int n = nums.length;
if (nums == null || n <= 2){
return Collections.emptyList();
}
Arrays.sort(nums);
List<List<Integer>> ret = new ArrayList<>();
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> value = new ArrayList<>();
value.add(nums[i]);
value.add(nums[j]);
value.add(nums[k]);
if (!ret.contains(value)){
ret.add(value);
}
}
}
}
}
return ret;
}
public static void main(String[] args) {
int[] nums = new int[]{-1,0,1,2,-1,-4};
System.out.println(threenum(nums));
}
}
三、双指针解法
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeNum_zhu {
public static List<List<Integer>> threenum(int[] nums){
//双指针法
Arrays.sort(nums);
List<List<Integer>> ret = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++){
//因为是排序过的,所以有元素>0,从前往后找就找不到
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i-1]){
//避免重复的三元组
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (left < right){
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0){
ret.add(Arrays.asList(nums[i],nums[left],nums[right]));
while (left < right && nums[left] == nums[left + 1]){
left++;
//避免重复元素
}
while (left < right && nums[right] == nums[right - 1]){
right--;
//避免重复元素
}
//找到一组后,继续寻找
left++;
right--;
}else if (sum > 0){
//如果和大于0,需减小值大小,右指针往左移动
right--;
}else{
//如果和小于0,需增加值大小,左指针往右移动
left++;
}
}
}
return ret;
}
public static void main(String[] args) {
int[] nums = new int[]{-1,0,1,2,-1,-4};
System.out.println(threenum(nums));
}
}