学习目标:
每日一题-三数之和学习内容:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。解法:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
ans = []
length = len(nums)
if nums == None or length < 3:
return ans
nums.sort()
for i in range(0,length,1):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i-1]:
continue
L = i+1
R = length-1
while L < R:
sum = nums[i] + nums[L] + nums[R]
if sum == 0:
ans.append([nums[i],nums[L],nums[R]])
while L<R and nums[L] == nums[L+1]:
L+=1
while L<R and nums[R] == nums[R-1]:
R-=1
L+=1
R-=1
elif sum < 0 :
L+=1
elif sum > 0:
R-=1
return ans