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; }