Python solution time limited exceeded


  • 0
    Z

    Hi all,
    I come out a python solution for this problem, but it indicates "Time Limited Exceeded", can anyone help me to modify my code?

    class Solution:
        # @param {integer[]} nums
        # @return {integer[][]}
        def threeSum(self, nums):
            self.nums = nums
            nums = sorted(nums)
            f = []
            n = len(nums)
            for i in xrange(n-1):
                j = i+1
                while nums[i]+nums[j] <= 0:
                    k = 0-(nums[i]+nums[j])
                    p = sorted(nums)
                    p.remove(p[j])
                    p.remove(p[i])
                    if k in p:
                        if sorted([nums[i],nums[j],k]) not in f:
                            f.append(sorted([nums[i],nums[j],k]))
                        if j < n-2:
                            j = j+1
                        else:
                            break
            return f
    

    thanks


  • 0
    A

    In the while loop, you have:

    if k in p:
           ###########
           if j < n-2:
                 j += 1
    

    but, if k is not in p,
    neither i or j changes.
    Then, your program gets stuck in the loop.

    So, you will need something like:

    if k in p:
           ########
       else:
           # handle the i and j value.
    

    And besides, you should know that

    p = sorted(nums)

    is O(nlog(n) time. and this statement is in s dual-loop,, so you have O(n3log(n)) time complexity.


Log in to reply
 

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