三数之和

思路:先固定一个数,然后剩下两个数用双指针,这样可以O(n2)时间完成

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        res = []
        
        for i in range(len(nums) - 2):
            if nums[i] >0:
                break
            if i > 0 and nums[i] == nums[i-1]:
                continue
            j = i + 1
            k = len(nums) - 1
            while j < k:
                if nums[i] + nums[j] + nums[k] == 0:
                    res.append([nums[i], nums[j], nums[k]])
                    k -= 1
                    while j < k and nums[k] == nums[k+1]:k -= 1
                    j += 1
                    while j < k and nums[j]==nums[j-1]:j += 1
                elif nums[i] + nums[j] + nums[k] > 0:
                    k -= 1
                    while j < k and nums[k] == nums[k+1]:k -= 1
                else:
                    j += 1
                    while j < k and nums[j]==nums[j-1]:j += 1
        return res
posted @ 2019-09-17 21:54  Dolisun  阅读(359)  评论(0编辑  收藏  举报