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.
Note: The solution set must not contain duplicate triplets.
1 public class Solution { 2 public List<List<Integer>> threeSum(int[] nums) { 3 List<List<Integer>> results = new ArrayList<List<Integer>>(); 4 if (nums.length < 3) { 5 return results; 6 } 7 Arrays.sort(nums); 8 if (nums[0] > 0 || nums[nums.length - 1] < 0) { 9 return results; 10 } 11 for (int i = 0; i < nums.length; i++) { 12 if (nums[i] > 0) { 13 break; 14 } 15 if (i > 0 && nums[i] == nums[i - 1]) { 16 continue; 17 } 18 int l = i + 1; 19 int r = nums.length - 1; 20 while (l < r) { 21 int t = nums[i] + nums[l] + nums[r]; 22 if (t == 0) { 23 List<Integer> list = new ArrayList<Integer>(); 24 list.add(nums[i]); 25 list.add(nums[l]); 26 list.add(nums[r]); 27 results.add(list); 28 while (l < r && nums[l + 1] == nums[l]) { 29 l++; 30 } 31 while (l < r && nums[r - 1] == nums[r]) { 32 r--; 33 } 34 l++; 35 r--; 36 } else if (t < 0) { 37 l++; 38 } else { 39 r--; 40 } 41 } 42 } 43 return results; 44 } 45 }

浙公网安备 33010602011771号