leetcode: 15. 3Sum

来源:互联网 发布:linux 查看最后500行 编辑:程序博客网 时间:2024/06/15 11:52

Problem

# Given an array S of n integers, are there elements a, b, c in S 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.## For example, given array S = [-1, 0, 1, 2, -1, -4],## A solution set is:# [#   [-1, 0, 1],#   [-1, -1, 2]# ]

AC

class Solution():     def threeSum(self, x):        x.sort()        res = []        for left in range(len(x) - 2):            if left == 0 or x[left] != x[left-1] and x[left] <= 0:                mid, right = left + 1, len(x) - 1                while mid < right:                    s = x[left] + x[mid] + x[right]                    if s == 0:                        res.append([x[left], x[mid], x[right]])                        mid, right = mid + 1, right - 1                        while mid < right and x[mid] == x[mid - 1]:                            mid += 1                        while mid < right and x[right] == x[right + 1]:                            right -= 1                    elif s < 0:                        mid += 1                    else:                        right -= 1        return resif __name__ == '__main__':    assert Solution().threeSum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]]    assert Solution().threeSum([1 ,1, 1, -2]) == [[-2, 1, 1]]
原创粉丝点击