3Sum LeetCode solution in Python

1
class Solution(object):
2
def threeSum(self, nums):
3
ans = []
4
nums.sort()
5

6
for i in range(len(nums)):
7
if nums[i] > 0:
8
break # after sorting, if the min > 0, we couldn't find such three values
9
if (
10
i > 0 and nums[i] == nums[i - 1]
11
): # ensure that nums[i] is not duplicated
12
continue
13
l, r = i + 1, len(nums) - 1
14
while l < r:
15
if nums[l] + nums[r] > -nums[i]:
16
r -= 1
17
elif nums[l] + nums[r] < -nums[i]:
18
l += 1
19
else:
20
ans.append([nums[i], nums[l], nums[r]])
21
# update l to get a different sum
22
l += 1
23
while nums[l] == nums[l - 1] and l < r:
24
l += 1
25
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0