15. 3Sum
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解题要点:
先从头开始遍历,然后同时用双指针处理找后面是否有符合条件的数字,加入到最终返回值里。(剪枝:重复的不作处理,直接跳过)
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
l = i + 1
h = len(nums) - 1
temp = 0 - nums[i]
while l < h:
if nums[l] + nums[h] > temp:
h -= 1
elif nums[l] + nums[h] < temp:
l += 1
else:
res.append([nums[i], nums[l], nums[h]])
while l < h and nums[l] == nums[l+1]: l += 1
while l < h and nums[h] == nums[h-1]: h -= 1
l += 1
h -= 1
return res
Last updated
Was this helpful?