Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
1 class Solution { 2 public List<List<Integer>> threeSum(int[] nums) { 3 int n = nums.length; 4 Arrays.sort(nums); 5 List<List<Integer>> ans = new LinkedList<>(); 6 for (int i = 0; i < n - 2; ++i) { 7 if (i == 0 || nums[i] != nums[i - 1]) { 8 int sum = 0 - nums[i]; 9 int l = i + 1, r = n - 1; 10 while (l < r) { 11 if (nums[l] + nums[r] == sum) { 12 ans.add(Arrays.asList(nums[i], nums[l], nums[r])); 13 while (l + 1 <= r && nums[l] == nums[l + 1])l++; 14 while (r - 1 >= l && nums[r] == nums[r - 1])r--; 15 l++; 16 r--; 17 } else if (nums[l] + nums[r] < sum) { 18 l++; 19 20 } else { 21 r--; 22 } 23 } 24 } 25 26 } 27 return ans; 28 } 29 }