15. 3Sum [python]

2019-03-11  本文已影响0人  Chiduru

【Description】
Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

【Idea】
先排序为有序数组。
之后参考2Sum的思想,当遍历index=0的数字时,它之后的数组作为独立list,求target=-nums[0]的值对。第一层复杂度为n, 之后2sum的求解参考分治法,复杂度为n, 所以总体为2n

此外的一个小tip,要求求解的list不能重复。这里有两种思路:

  1. 在遍历时增加限制条件,当后一项元素与当前元素相等时,前跳一位(两层遍历都需跳)
  2. 找到目标解时,result_list.append()处增加限制:
    将[n1, n2, n3]排序转为字符,判断是否与之前重复。但需要额外的存储空间,时间复杂度也相对高。不是很推荐
''.join([str(i) for i in [nums[i], nums[left], nums[right]]])

【Solution】

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        tag = []
        result = list()
        nums = sorted(nums)
        for i in range(len(nums)-2):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            temp_sum = -nums[i]
            left = i + 1
            right = len(nums) - 1
            while left < right:
                if nums[left] + nums[right] < temp_sum:
                    left += 1
                elif nums[left] + nums[right] > temp_sum:
                    right -= 1
                else:
                    result.append([nums[i], nums[left], nums[right]])
                    while left < right and nums[left] == nums[left + 1]:
                        left += 1
                    while left < right and nums[right] == nums[right - 1]:
                        right -= 1
                    left += 1
                    right -= 1
        return result
上一篇下一篇

猜你喜欢

热点阅读