Three sum algorithm solution

后端 未结 4 1079
迷失自我
迷失自我 2020-12-16 23:53

Original Problem Statement:

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

4条回答
  •  天命终不由人
    2020-12-17 00:27

    I'd like to add the answer you claimed(in the comment) to post:

    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            def twoSum(self, nums, target):
                targ = target
                for index, i in enumerate(nums):
                    targ -= i
    
                    # if targ in nums[index+1:]:
                    #    return [nums[index], nums[nums[index+1:].index(targ)+index+1]]
                    _num = nums[:index] + nums[index+1:]
                    if targ in _num: 
                        return [i, targ]
                    else:
                        targ = target
                return None
            res = []
            for index, i in enumerate(nums):
                target = i * -1
                num = nums[:index] + nums [index+1:]
                ans = twoSum(self, num, target)
                if ans != None:
                    temp = ans + [i]
                    temp.sort()
                    res.append(temp)
            print(res)
            import itertools
            res.sort()
            res = list(res for res,_ in itertools.groupby(res))
            return res
    

    I have only run it my brain and hope it is right.

提交回复
热议问题