0015. 3Sum
Medium | Math + Hash Table | 624 ms (97.81%), 17.8 MB (32.19%)
Source: LeetCode - 3Sum GitHub: Solution / Performance
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
Notice that the solution set must not contain duplicate triplets.
Same idea as 0001. Two Sum with more case handlings.
There are several different cases for the sum of three numbers that equal ZERO.
0, 0, 0
-n, 0, n
-n, -m, m+n
-n-m, n, m
We need to use a specific data structure (Set in Python) to solve this problem with an extra constraint that the solution set must not contain duplicate triplets.
We store negative numbers, ZERO, positive numbers into a list and a set separately. Then, we use the numbers stored in the list to calculate the remaining value and then search it in the Set. Once we find it, we add it to the other Set as the final answer.
Last updated