python 15. 3Sum.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 15. 3Sum.py相关的知识,希望对你有一定的参考价值。

# Time: O(n^2)
# Space:
# 15. 3Sum
# Edge case: duplicate 
'''
1. IO
S = [-1, 0, 1, 2, -1, -4] → 
[
  [-1, 0, 1],
  [-1, -1, 2]
]
2. 
'''

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums = sorted(nums)
        target = []
        for i in range(len(nums)-2):
            if i == 0 or nums[i] != nums[i-1]:
                j = i + 1
                k = len(nums) - 1
                while j < k:
                    if nums[i] + nums[j] + nums[k] < 0:
                        j += 1
                    elif nums[i] + nums[j] + nums[k] > 0:
                        k -= 1
                    else:
    #                     tmp = [nums[i],nums[j],nums[k]]  # time-consuming 
    #                     if tmp not in target:
    #                         target.append( tmp )
                        target.append([nums[i],nums[j],nums[k]])
                        j += 1
                        k -= 1
                        while j < k and nums[j] == nums[j-1]: # better than check if there exists in current list 
                            j += 1
                        while j < k and nums[k] == nums[k+1]:
                            k -= 1
    #             while i > 0 and i < len(nums) - 2 and  nums[i] == nums[i-1]:
    #                 i += 1
        return target   

以上是关于python 15. 3Sum.py的主要内容,如果未能解决你的问题,请参考以下文章

Day15 - Python基础15 模块学习-selectors

python-15:装饰函数

python15-day17

openSuse 15.2 没有 python38 pip

Ubuntu15.04 python升级到python-3.6.x

Python基础-15模块-包-库