Skip to content

Commit 0e4e164

Browse files
committed
[WHYjun] WEEK 02 solutions - (4/5)
1 parent b34fb6d commit 0e4e164

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

3sum/WHYjun.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
answer = []
4+
sortedNums = sorted(nums)
5+
6+
for i in range(len(sortedNums)):
7+
# skip if same to avoid dup
8+
if i > 0 and sortedNums[i] == sortedNums[i-1]:
9+
continue
10+
11+
# use two pointers
12+
j = i + 1
13+
k = len(sortedNums) - 1
14+
15+
while j < k:
16+
total = sortedNums[i] + sortedNums[j] + sortedNums[k]
17+
18+
if total == 0:
19+
answer.append([sortedNums[i], sortedNums[j], sortedNums[k]])
20+
j += 1
21+
# skip if same to avoid dup
22+
while sortedNums[j] == sortedNums[j-1] and j < k:
23+
j += 1
24+
elif total < 0:
25+
j += 1
26+
else:
27+
k -= 1
28+
29+
return answer
30+

0 commit comments

Comments
 (0)