题解 | #三数之和#

三数之和

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

字典dict记录输入数组中数字出现次数,当数字重复出现3次时,跳过当前数字执行后续语句,以降低程序运行时间

class Solution:
    def threeSum(self , num: List[int]) -> List[List[int]]:
        # write code here
        n = len(num)
        if n <= 2 or (n == 3 and sum(num) != 0):
            return None
        result = []
        dict = {}
        for i in range(n):
            if num[i] not in dict:
                dict[num[i]] = 1
            else:
                if dict[num[i]] > 3:
                    continue
                dict[num[i]] += 1
            for j in range(n - i - 1):
                if num[i + j + 1] not in dict:
                    dict[num[i + j + 1]] = 1
                else:
                    if dict[num[i + j + 1]] > 3:
                        continue
                if -(num[i] + num[i + j + 1]) in num[i + j + 2:]:
                    a = [num[i], num[i + j + 1], -(num[i] + num[i + j + 1])]
                    a.sort()
                    if a not in result:
                        result.append(a)
        return result
全部评论

相关推荐

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