题目:
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]
]
题意: 在给定的一个数组里找出三个数,使之和为0,最后返回包含所有可行解的list,注意每一个解里的元素是按照升序排序的,最后解的集合不允许包含相同的解。
思路: 此题的一个解法就是使用三个指针,先对数组进行升序或者降序排序,然后固定一个指针i使之从数组头部遍历至尾部,再针对i之后的元素用两个指针采用夹逼法找到另外两个数,使得三个数的和为0。此题的一个需要注意的问题就是去重,可以选择在找到所有存在的情况后调用set函数去重,也可以边查找边去重。因为采用夹逼的方法,可以降低一个维度的复杂度,因此,此题的时间复杂度为
O
(
n
2
)
O(n^2)
O(n2)。至于还有没有更好的解法,未知。
代码仅供参考:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = len(nums)
nums = sorted(nums)
solutions = []
for i in range(n-2):
if i != 0 and nums[i] == nums[i-1]:
continue
else:
re_nums = nums[i+1:]
target = 0 - nums[i]
j = 0
k = len(re_nums)-1
while j < k:
if re_nums[j] + re_nums[k] == target:
solutions.append((nums[i], re_nums[j], re_nums[k]))
j += 1
k -= 1
#去重
while j < k and re_nums[j] == re_nums[j-1]:
j+=1
while j < k and re_nums[k] == re_nums[k+1]:
k-=1
elif re_nums[j] + re_nums[k] < target:
j += 1
else:
k -= 1
return solutions