-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_15.py
More file actions
39 lines (36 loc) · 1.09 KB
/
leetcode_15.py
File metadata and controls
39 lines (36 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# coding=utf-8
from typing import List
class Solution:
"""
三数之和
"""
def three_sum(self, nums: List[int]) -> List[List[int]]:
"""
Time: O(n^2), Space: O(1)
:param nums:
:return:
"""
nums.sort()
res = []
k = len(nums) - 1
while k >= 2:
if nums[k] < 0:
break
target, left, right = -nums[k], 0, k - 1
while left < right:
if nums[left] + nums[right] < target:
left += 1
elif nums[left] + nums[right] > target:
right -= 1
else:
res.append([nums[left], nums[right], nums[k]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
while k >= 2 and nums[k] == nums[k - 1]:
k -= 1
k -= 1
return res