15. 3Sum

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

本题应该是leetCode官网在近期添加了一个测试个例,网上好多的解决方法都是TLE。本人刚好找到一位博主分享,参考地址已在最后贴出。

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        length, res = len(nums), []
        nums.sort()
        # length-2 的原因是3Sum是3个数相加, 下方变量left和right为最后两个
        # 数,所以没有必要令 i 循环最后两位数。
        for i in range(length - 2):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            left, right = i + 1, length - 1
            while left < right:
                result = nums[i] + nums[left] + nums[right]
                if result == 0:
                    res.append([nums[i], nums[left], nums[right]])
                    left += 1;
                    right -= 1
                    while left < right and nums[left] == nums[left - 1]: left += 1
                    while left < right and nums[right] == nums[right + 1]: right -= 1
                elif result < 0:
                    left += 1
                else:
                    right -= 1

        return res  

参考:https://blog.csdn.net/fuxuemingzhu/article/details/83115850

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容