15. 3Sum

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        length=len(nums)
        nums=sorted(nums)
        res=[]
        for i in range(length-2):
            if i>0 and nums[i]==nums[i-1]:
                continue
            left=i+1
            right=length-1
            while(left<right):
                tmp=[]
                target=nums[i]
                cur=nums[left]+nums[right]
                if target+cur==0:
                    tmp.append(target)
                    tmp.append(nums[left])
                    tmp.append(nums[right])
                    res.append(tmp)
                    left+=1
                    right-=1
                    while left<length and nums[left]==nums[left-1]:
                        left+=1
                    while right>0 and nums[right]==nums[right+1]:
                        right-=1
                elif target+cur<0:
                    left+=1
                else:
                    right-=1
        return res

  

posted @ 2018-01-07 20:49  PirateLHX  阅读(104)  评论(0编辑  收藏  举报