题解 | #三数之和#

三数之和

https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711

p

class Solution:
    def is_same(self,lit,l):
        """
		lit:最终存储的可能数组
		l:可能的答案
		判断l是否已经存在,手动去重(可能时间要比代码里去重长)
		"""
		for i in range(len(lit)):
            if lit[i] == l:
                return False
        return True
    def threeSum(self , num: List[int]) -> List[List[int]]:
        # write code here
        num.sort()
        n = len(num)
        res = []#存储最终数组
        for i in range(n-2):
            if num[i] <= 0:
                left = i+1
                right = n-1
                while left<right:
                    if num[left] + num[right] == abs(num[i]):
                        r = [num[i],num[left],num[right]]
                        if self.is_same(res,r):
                            res.append(r)
                        left +=1
                        right -= 1 
                    elif num[left] + num[right] < abs(num[i]):
                        left +=1
                    else:
                        right -= 1
            else:
                continue
        return res

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务