Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.给定一个整数数组s,咱们要找出s中是否有三个不一样元素的加和等于0,若是有,输出全部知足条件的序列。要求序列不重复。数组
For example, 输入数组S = [-1, 0, 1, 2, -1, -4],
返回的结果集应该是:
[
[-1, 0, 1],
[-1, -1, 2]
]指针
public List<List<Integer>> threeSum(int[] nums) { int length = nums.length; List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(nums); for(int i=0;i<length-2;i++){ //防止重复序列 if(i ==0 || (i>0 && nums[i] != nums[i-1])){ int low = i+1; int high = length-1; int target = -nums[i]; while(low < high){ if(nums[low]+nums[high] == target){ res.add(Arrays.asList(nums[i], nums[low], nums[high])); while(low < high && nums[low] == nums[low+1])low++; while(low < high && nums[high] == nums[high-1])high--; low++; high--; }else if(nums[low]+nums[high] < target){ low++; }else{ high--; } } } } return res; }