==============================================================================
【id】#15
【title】 3Sum
【description】
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]
]
【idea】
双指针!!!!!极其特别重要的方法!!
首先将数组排序得到有序数组。
然后找到一个固定的数,另外两个数加和为固定数的相反数。因为数组是有秩序的,所以固定数必须是非负数,因为如果是正数,后边的所有数都是正数,不会加和为负数。
找到固定数之后,固定数之后的数组手尾为两个指针,如果加和为target,移动指针,并且忽略掉相同的元素避免最后结果重复。
【code】
class Solution(object):
def threeSum(self, nums):
if len(nums) <3 : return []
nums = sorted(nums)
# print(nums)
length = len(nums)
res = []
for i in range(length):
if nums[i] > 0 : break
if i >0 and nums[i] == nums[i-1]: continue
target = -nums[i]
# print(target)
low = i+1
high = length-1
while high >low:
if nums[low] + nums[high] == target :
res.append([nums[i],nums[low], nums[high]])
while low <high and nums[low] == nums[low+1]: low += 1
while low <high and nums[high] == nums[high-1]: high -= 1
low += 1
high -= 1
elif nums[low] + nums[high] > target: high -= 1
else: low += 1
return res