[LeetCode] 15. 3Sum
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.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
Thought process:
Sort the array. Iterate through the sorted array. For each element, iterate through the elements to its right using two pointers: one from the right of this element, the other from end of the array.
- If nums[i] + nums[j] + nums[k] < 0, increment the left pointer.
- If equal, add indices to result and update both pointers.
- Otherwise, decrement the right pointer.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> triplets = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { while (i > 0 && i < nums.length && nums[i] == nums[i - 1]) { i++; } int j = i + 1; int k = nums.length - 1; while (j < k) { while (j > i + 1 && j < k && nums[j] == nums[j - 1]) { j++; } while (k < nums.length - 1 && k > j && nums[k] == nums[k + 1]) { k--; } if (j == k) { break; } int sum = nums[i] + nums[j] + nums[k]; if (sum < 0) { j++; } else if (sum == 0) { List<Integer> triplet = new ArrayList<>(); triplet.add(nums[i]); triplet.add(nums[j]); triplet.add(nums[k]); triplets.add(triplet); j++; k--; } else { k--; } } } return triplets; } } |
Time complexity:
Sorting takes O(nlogn). Loop takes O(n^2). The overall time complexity is O(n^2).
Comments
Post a Comment