给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
package leetCode_5_8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author : caoguotao
* @date 创建时间:2019年5月8日 下午5:26:02
* @version 1.0
* @parameter
* @since
* @return
*/
public class Solution15 {
public static void main(String[] args) {
int[] nums = {-2,0,1,1,2};
List<List<Integer>> list = new ArrayList<List<Integer>>();
list = threeSum(nums);
for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).get(0) + " " +
list.get(i).get(1) + " " +
list.get(i).get(2));
}
}
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2;) {
int first = i + 1;
int last = nums.length - 1;
while(first < last) {
List<Integer> l = new ArrayList<Integer>();
if(nums[first] + nums[last] + nums[i] == 0) {
l.add(nums[i]);
l.add(nums[first]);
l.add(nums[last]);
list.add(l);
while(first < nums.length - 2 && nums[first] == nums[first + 1]) {
first++;
}
first++;
continue;
}
if(nums[first] + nums[last] + nums[i] > 0) {
last--;
continue;
}
if(nums[first] + nums[last] + nums[i] < 0) {
first++;
continue;
}
}
while(i < nums.length - 2 && nums[i] == nums[i + 1]) {
i++;
}
i++;
}
return list;
}
}