leetcode-015-3Sum

leetcode-015-3Sum 三数之和


1. 题目

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

2. 解

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
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
count = len(nums)
collect = []
for i in range(count):
left = i+1
right = count-1
if i >0 and nums[i] == nums[i-1]:
left +=1
continue
while left < right:
sum = nums[i] + nums[left] + nums[right]
if sum == 0:
col = [nums[i],nums[left],nums[right]]
collect.append(col)
left+=1
right-=1
while nums[left] == nums[left-1] and left < right:
left+=1
while nums[right] == nums[right+1] and left < right:
right-=1
if sum<0:
left+=1
elif sum > 0:
right-=1
return collect