3 Sum 解答
Question
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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
Solution
First, we sort the array and then implement 2 pointers to get 2 Sum. Time complexity is O(n2)
Notice here, we need to consider duplicates in result.
1 public class Solution { 2 public List<List<Integer>> threeSum(int[] nums) { 3 if (nums == null || nums.length < 1) 4 return null; 5 Arrays.sort(nums); 6 int length = nums.length; 7 List<List<Integer>> result = new ArrayList<List<Integer>>(); 8 for (int i = 0; i <= length - 3; i++) { 9 // Remove duplicates 10 if (i > 0 && nums[i] == nums[i - 1]) 11 continue; 12 int target = 0 - nums[i]; 13 int l = i + 1, r = length - 1; 14 while (l < r) { 15 if (nums[l] + nums[r] == target) { 16 result.add(Arrays.asList(nums[i], nums[l], nums[r])); 17 while (l < r && nums[l] == nums[l+1]) l++; 18 while (l < r && nums[r] == nums[r-1]) r--; 19 l++; 20 r--; 21 } else if (nums[l] + nums[r] < target) { 22 l++; 23 } else { 24 r--; 25 } 26 } 27 } 28 return result; 29 } 30 }