思路:
- 定义三个下角标指针,k,i,j>>>>>i=k+1,j=n-1 (n为数组长度)
- num[k] > 0 ,如果num[k]比0大的话,num[i] 和 num[j] 就更大了,三个数加起来不可能为0
- i<j and num[i-1]=num[i] ; i++ ; i<j and num[j+1]=num[j]: j- -
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return []
# 对nums 进行排序
nums=sorted(nums)
n=len(nums)
res=[]
for k in xrange(n-2):
if nums[k]>0:
break
if k>0 and nums[k]==nums[k-1]:
continue
i,j=k+1,n-1
while i<j:
temp=nums[i]+nums[j]+nums[k]
if temp>0:
j-=1
while i<j and nums[j]==nums[j+1]:
j-=1
elif temp<0:
i+=1
while i<j and nums[i]==nums[i+1]:
i+=1
else:
res.append([nums[i],nums[j],nums[k]])
while i<j and nums[i]==nums[i-1]:
i+=1
while i<j and nums[j+1]==nums[j]:
j-=1
return res