Python solution. Using two sum and sort. beat 95%


  • 2
    L
    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            nums.sort()
            result,visited = set(),{}
            for i in xrange(len(nums)-2):
                table,target = {},-nums[i]
                if nums[i] not in visited:
                    for j in xrange(i+1,len(nums)):
                        if nums[j] not in table:    table[target - nums[j]] = j
                        else:   result.add((nums[i],target-nums[j],nums[j]))
                    visited[nums[i]] = 1
            return list(result)
    

  • 0
    D

    Thanks for this solution. I enjoyed understanding it since my own solution was quite slow.
    I added one line of code:

    for i in xrange(len(nums)-2):
           if nums[i] <=0:
                 .... etc.
    

    to make it even faster :-)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.