|
| 1 | +""" |
| 2 | +15. 3Sum |
| 3 | +https://leetcode.com/problems/3sum/description/ |
| 4 | +
|
| 5 | +Solution: |
| 6 | + - Sort the list |
| 7 | + - Iterate through the list |
| 8 | + - For each element, find the two elements that sum up to -element |
| 9 | + - Use two pointers to find the two elements |
| 10 | + - Skip the element if it is the same as the previous element |
| 11 | + - Skip the two elements if they are the same as the previous two elements |
| 12 | + - Add the set to the output list |
| 13 | +
|
| 14 | + Example: |
| 15 | + ----------------------------------------- |
| 16 | + low : | |
| 17 | + high: | |
| 18 | + i : | |
| 19 | + [-4,-1,-1,0,1,2] |
| 20 | +
|
| 21 | + ----------------------------------------- |
| 22 | + low : | |
| 23 | + high: | |
| 24 | + i : | |
| 25 | + [-4,-1,-1,0,1,2] |
| 26 | +
|
| 27 | + ... no possible set with i=-4, and high=2 |
| 28 | +
|
| 29 | + ----------------------------------------- |
| 30 | + low : | |
| 31 | + high: | |
| 32 | + i : | |
| 33 | + [-4,-1,-1,0,1,2] |
| 34 | +
|
| 35 | +
|
| 36 | +Time complexity: O(n^2) |
| 37 | + - O(nlogn) for sorting |
| 38 | + - O(n^2) for iterating through the list and finding the two elements |
| 39 | + - Total: O(n^2) |
| 40 | +Space complexity: O(n) |
| 41 | + - O(n) for the output list |
| 42 | + - O(n) for the prevs dictionary |
| 43 | + - O(n) for the prevs_n set |
| 44 | + - Total: O(n) |
| 45 | +""" |
| 46 | + |
| 47 | + |
| 48 | +from typing import List |
| 49 | + |
| 50 | + |
| 51 | +class Solution: |
| 52 | + def threeSum(self, nums: List[int]) -> List[List[int]]: |
| 53 | + nums = sorted(nums) |
| 54 | + output = [] |
| 55 | + prevs = dict() |
| 56 | + prevs_n = set() |
| 57 | + |
| 58 | + for i in range(len(nums) - 2): |
| 59 | + n_i = nums[i] |
| 60 | + |
| 61 | + if n_i in prevs_n: |
| 62 | + continue |
| 63 | + else: |
| 64 | + prevs_n.add(n_i) |
| 65 | + |
| 66 | + low, high = i + 1, len(nums) - 1 |
| 67 | + while low < high: |
| 68 | + n_low = nums[low] |
| 69 | + n_high = nums[high] |
| 70 | + if n_i + n_low + n_high == 0: |
| 71 | + if not f"[{n_i},{n_low},{n_high}]" in prevs: |
| 72 | + prevs[f"[{n_i},{n_low},{n_high}]"] = 1 |
| 73 | + output.append([n_i, n_low, n_high]) |
| 74 | + low += 1 |
| 75 | + high -= 1 |
| 76 | + |
| 77 | + elif n_i + n_low + n_high < 0: |
| 78 | + low += 1 |
| 79 | + |
| 80 | + elif n_i + n_low + n_high > 0: |
| 81 | + high -= 1 |
| 82 | + |
| 83 | + return output |
0 commit comments