Reference: LeetCode
Difficulty: Medium
Problem
Given an array nums of
n
integers, are there elementsa, b, c
in nums such thata + 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.
- Elements are not necessarily unique.
- Each element is only used once.
Example:
1 | Given array nums = [-1, 0, 1, 2, -1, -4], |
Follow up: Reduce to $O(N^2)$ time complexity.
Analysis
Brute-Force
Two Issues:
Used Each Element Once
: Solve byj = i + 1
andk = j + 1
.No Duplicate Triplets
: Solve byif (i > 0 && nums[i] == nums[i - 1]) continue;
.
Note: Use Arrays.asList(nums[i], nums[j], nums[k])
to make a new list quickly.
1 | public List<List<Integer>> threeSum(int[] nums) { |
Time: $O(N^3)$
Space: $O(1)$
Two Pointers
- Sort first.
- For each element
nums[i]
, use modified two-pointer approach.- When
nums[j] + nums[k] == target
:- Update
j
andk
both. - Add two
while-loop
to handle Issue #2.
- Update
- When
1 | public List<List<Integer>> threeSum(int[] nums) { |
Time: $O(N^2)$
Space: $O(1)$