SHOW:
|
|
- or go back to the newest paste.
1 | class Solution: | |
2 | def threeSum(self, nums: List[int]) -> List[List[int]]: | |
3 | newSums = [] | |
4 | nums.sort() | |
5 | ||
6 | #This has to be minus 2 because your forward J Pointer will cause a tuple duplicate. | |
7 | for i in range(len(nums)- 2): | |
8 | ||
9 | #We need to skip duplicate elements from the left side as well. (This took me 15 minutes to realize). | |
10 | if i > 0 and nums[i] == nums[i-1]: | |
11 | continue | |
12 | #You have to reassign these accordingly during each loop. If you do it before this check you run into the same problem^. | |
13 | j = i + 1 | |
14 | k = len(nums) - 1 | |
15 | ||
16 | while j < k: | |
17 | if (nums[i] + nums[j] + nums[k]) == 0: | |
18 | newSums.append([nums[i], nums[j], nums[k]]) | |
19 | ||
20 | #Avoiding another duplication problem i ran into. | |
21 | if k < len(nums) - 1 and nums[k] == nums[k + 1]: | |
22 | continue | |
23 | j+=1 | |
24 | k-=1 | |
25 | ||
26 | elif nums[i] + nums[j] + nums[k] > 0: | |
27 | k -= 1 | |
28 | elif nums[i] + nums[j] + nums[k] < 0: | |
29 | j += 1 | |
30 | ||
31 | return newSums |