• LeetCode 3Sum


    LeetCode解题之3Sum


    原题

    找出一个列表中全部和为零的三元组。

    要求求出的三元组中没有反复。

    注意点:

    • 三元组中的数字要按增序排列(a<=b<=c)
    • 结果集中没有反复的三元组

    样例:

    输入: nums=[-1, 0, 1, 2, -1, -4]
    输出: [[-1, -1, 2], [-1, 0, 1]]

    解题思路

    求一个列表中全部和为零的二元组的一种思路是先把列表排序,再用两个指针从两头向中间移动。

    假设前后两个数的和小于0,则左指针右移;假设和大于0,则右指针左移。

    求三元组时能够參考这样的做法,第一个数a确定后,能够理解为求列表中和为-a的二元组。因为不要考虑反复的元组,遇到反复的数能够直接跳过。

    AC源代码

    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            # Sorted array can save a lot of time
            nums.sort()
            result = []
            i = 0
            while i < len(nums) - 2:
                j = i + 1
                k = len(nums) - 1
                while j < k:
                    l = [nums[i], nums[j], nums[k]]
                    if sum(l) == 0:
                        result.append(l)
                        j += 1
                        k -= 1
                        # Ignore repeat numbers
                        while j < k and nums[j] == nums[j - 1]:
                            j += 1
                        while j < k and nums[k] == nums[k + 1]:
                            k -= 1
                    elif sum(l) > 0:
                        k -= 1
                    else:
                        j += 1
                i += 1
                # Ignore repeat numbers
                while i < len(nums) - 2 and nums[i] == nums[i - 1]:
                    i += 1
            return result
    
    
    if __name__ == "__main__":
        assert Solution().threeSum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]]

    欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

  • 相关阅读:
    01_python修改递归最大深度
    所有失去的会以另一种形式归来
    长大了,总有那么一两次,你会为重视的人奔跑,因为是对的人,走路真的来不及
    urllib的使用
    linux常用命令
    CentOS7安装软件后检索获取密钥失败的解决方法
    urllib3的使用
    拖延
    centos下软件的安装
    曾经
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/7238322.html
Copyright © 2020-2023  润新知