My simple enough solution by Python (a little slow, 338ms)


  • 0
    T
    class Solution:
        # @return a list of lists of length 3, [[val1,val2,val3]]
        def threeSum(self, num):
            check = {}    #record the count of each value
            ans = []
            for val in num:
                if check.has_key(val):
                    check[val] += 1
                else:
                    check[val] = 1
            for key1 in check:
                for key2 in check:
                    key3 = 0 - key1 - key2
                    if check.has_key(key3):
                        temp1 = check[key1]
                        temp2 = check[key2]
                        temp3 = check[key3]
                        check[key1] -= 1
                        check[key2] -= 1
                        check[key3] -= 1
                        if check[key1] >= 0 and check[key2] >= 0 and check[key3] >= 0:
                            if sorted([key1, key2, key3]) not in ans:
                                ans.append(sorted([key1, key2, key3]))
                        check[key1] = temp1
                        check[key2] = temp2
                        check[key3] = temp3
            return ans

Log in to reply
 

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