给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路:遍历数组nums,对其中的每一个数,看看能否在nums中找到另外两个数和它相加等于0。
class Solution:
def threeSum(self, nums):
res = []
for i in range(len(nums)):
for x,y in enumerate(nums):
if -(nums[i]+y) in nums:
if nums.index(-(nums[i]+y)) != x and i != x and nums.index(-(nums[i]+y)) != i:
num = [nums[i],y,-(nums[i]+y)]
num.sort()
res.append(num)
result = []
for j in res:
if j not in result:
result.append(j)
return result
s = Solution()
res = s.threeSum([-1, 0, 1, 2, -1, -4])
print(res)
这个代码测试的时候超时了。
思路2:首先对数组从小到大排序,从第一个数开始遍历,若该数大于0,后面的数不可能与其相加和为0,所以跳过;否则该数可能是满足要求的第一个数,这样可以转化为求后面数组中两数之和为该数的相反数的问题。定义两个指针一前一后,若找到两数之和满足条件则加入到解集中;若大于和则后指针向前移动,反之则前指针向后移动,直到前指针大于等于后指针。这样遍历第一个数直到数组的倒数第3位。注意再求和过程中首先判断该数字是否与前面数字重复,保证解集中没有重复解。
http://www.cnblogs.com/wmx24/p/8989800.html
class Solution:
def threeSum(self, nums):
nums.sort()#先对数组排序
res =[]
i = 0
for i in range(len(nums)):
if i == 0 or nums[i]>nums[i-1]:
l = i+1
r = len(nums)-1
while l < r:
s = nums[i] + nums[l] +nums[r]
if s ==0:
res.append([nums[i],nums[l],nums[r]])
l +=1
r -=1
#判断答案是否数字重复
while l < r and nums[l] == nums[l-1]:
l += 1
while r > l and nums[r] == nums[r+1]:
r -= 1
elif s>0:
r -=1
else :
l +=1
return res
s = Solution()
res = s.threeSum([-1, 0, 1, 2, -1, -4])
print(res)