leetcode 15 3sum python

先说一下自己的想法,这道题用暴力搜索肯定是不行的,自己想到计算两个数的和,之后使用二分查找,找到-(两数之和),最后虽然结果是正确的,但是却超出了时间限制。在博客上看了一些人的代码,提交还是超出时间限制,最后采用了双指针的方法顺利通过。

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

猜你喜欢

转载自blog.csdn.net/weixin_41722370/article/details/83512142