class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]def threeSum(self, num):
num.sort()
res = []
for i in range(len(num)-2):
if i == 0 or num[i] > num[i-1]:
left = i + 1; right = len(num) - 1
while left < right:
if num[left] + num[right] == -num[i]:
res.append([num[i], num[left], num[right]])
left += 1; right -= 1
while left < right and num[left] == num[left-1]: left +=1
while left < right and num[right] == num[right+1]: right -= 1
elif num[left] + num[right] < -num[i]:
while left < right:
left += 1
if num[left] > num[left-1]: breakelse:
while left < right:
right -= 1
if num[right] < num[right+1]: breakreturn res
补充个人代码:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
#lens=len(nums)
result={}
nums.sort() #排序的意义在于便于排除已经处理的数字,若是与上次处理的数字相同,则不处理
k=-1
for i in range(0,len(nums)-2):
other1=0-nums[i]
if i!=0 and nums[i]==nums[i-1]:#排序后若有重复数字,一定是相邻的,且结果一定重复,要排除
continue
for j in range(i+1,len(nums)-1):
if j!=i+1 and nums[j]==nums[j-1]:
continue
for m in range(len(nums)-1,j,-1):
if nums[j]+nums[m]==other1:
k+=1
result[k]=[nums[i],nums[j],nums[m]]
break
return result.values()
根据参考重新更改代码:
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self,nums):
nums.sort()
r=[]
for i in range(0,len(nums)-2):
if i == 0 or nums[i] > nums[i-1]:
left = i + 1; right = len(nums) - 1
while left<right:
if nums[left]+nums[right]==-nums[i]:
r.append([nums[i],nums[left],nums[right]])
left+=1;right-=1 #左右两边都要改变,只改变左边的值,则和不为0或是和为0但重复结果
while left<right and nums[left]==nums[left-1]: left+=1 #去除重复数字的搜索
while left<right and nums[right]==nums[right+1]: right-=1
elif nums[left]+nums[right]<-nums[i]: #小于和,说明不够大,左边向右移
while left<right:
left+=1
if nums[left]!=nums[left-1]:break#循环去除重复数字的处理
else:
while left<right:
right-=1
if nums[right]!=nums[right+1]:break
return r