@author: ZZQ
@software: PyCharm
@file: threeSum.py
@time: 2018/10/6 19:47
说明:给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路:先对数组排序,然后找满足 nums[first] + nums[last] + nums[middle] = 0 的三个数。同时去掉重复的三元组。
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
out_index = []
if len(nums) == 0:
return []
nums.sort()
for middle in range(len(nums)-2):
if middle == 0 or nums[middle] > nums[middle-1]:
first = middle + 1
last = len(nums) - 1
while first < last:
if nums[first] + nums[last] + nums[middle] == 0:
out_index.append([nums[first], nums[middle], nums[last]])
first += 1
last -= 1
while nums[first] == nums[first-1] and first < last:
first += 1
while nums[last] == nums[last+1] and first < last:
last -= 1
elif nums[first] + nums[last] + nums[middle] < 0:
first += 1
else:
last -= 1
return out_index