class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def threeSum(self, nums):
"O(n**2), for k-sum, time complexity is O(max{nlogn,n**(k-1)})"
nums.sort()
res,l=[],len(nums)
for i in range(l):
if i>0 and nums[i]==nums[i-1]:
continue
m,r=i+1,l-1
while m<r:
tmp=nums[i]+nums[m]+nums[r]
if tmp<0:
m+=1
elif tmp>0:
r-=1
else:
res.append([nums[i],nums[m],nums[r]])
while m<r and nums[m]==nums[m+1]: m+=1
while m<r and nums[r]==nums[r-1]: r-=1
m,r=m+1,r-1
return res
# @param {integer[]} nums
# @return {integer[][]}
def threeSum(self, nums):
"O(n**2), for k-sum, time complexity is O(max{nlogn,n**(k-1)})"
nums.sort()
res,l=[],len(nums)
for i in range(l):
if i>0 and nums[i]==nums[i-1]:
continue
m,r=i+1,l-1
while m<r:
tmp=nums[i]+nums[m]+nums[r]
if tmp<0:
m+=1
elif tmp>0:
r-=1
else:
res.append([nums[i],nums[m],nums[r]])
while m<r and nums[m]==nums[m+1]: m+=1
while m<r and nums[r]==nums[r-1]: r-=1
m,r=m+1,r-1
return res
5074

被折叠的 条评论
为什么被折叠?



