leetcode刷题十一
题目叙述
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
题目解答
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
source = nums
l = len(nums)
if l < 3:
return []
nums.sort()
if nums[0] > 0:
return []
if nums[l - 1] < 0:
return []
big = []
small = []
out = []
for i in range(l):
if nums[i] < 0:
small.append(nums[i])
if nums[i] > 0:
big.append(nums[i])
for i in small:
nums.remove(i)
for i in big:
nums.remove(i)
if len(nums) >= 3:
out.append([0, 0, 0])
if len(small) == 0 or len(big) == 0:
return out
# print(source, nums)
if 0 in nums:
for i in small:
if -i in big:
out.append([i, 0, -i])
for i in small:
for j in big:
small.remove(i)
big.remove(j)
if - (i + j) in small or - (i + j) in big:
out.append([i, -(i+j), j])
small.append(i)
small.sort()
big.append(j)
big.sort()
else:
for i in small:
for j in big:
small.remove(i)
big.remove(j)
if - (i + j) in small or - (i + j) in big:
out.append([i, -(i+j), j])
small.append(i)
small.sort()
big.append(j)
big.sort()
res = out
out = []
for i in res:
i.sort()
if i in out:
continue
else:
out.append(i)
return