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]
]Follow up: 如果不sort能怎么做
Thoughts:
a + b + c =0 <=> a + b = -c
Traverse each element : a target of two sum. Search direction should be consistent with the direction of traverse order(avoid duplicates).
[code 1: using map]: O(n^2) + Extra Space (HashMap/ unordered_map) : https://leetcode.com/problems/3sum/discuss/163934/Efficient-Java-Solution
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) map.put(nums[i], i); // val , last index
for(int i = 0 ; i < nums.length - 2; i++){
for(int j = i + 1; j < nums.length -1; j++){
int target = 0 - nums[i] - nums[j];
if (map.containsKey(target) && map.get(target) > j){
res.add(Arrays.asList(nums[i], nums[j], target));
j = map.get(nums[j]); // Taking the last index of j to remove duplicate
}
}
i = map.get(nums[i]); // Taking the last index of i to remove duplicate
}
return res;
}
}FollowUp: without Sort https://leetcode.com/problems/3sum/discuss/110507/Golang-~n2+n-worst-case-no-sort-no-deduplication-O(n2)-beats-50
Python
[code 2: two pointer]: O(n^2) without extra space (ordered_map)
Variation: Expand sum to be 0 as in general case
Special thanks: 洗刷刷 for the reference!
Last updated
Was this helpful?