Can't understand why TLE. Python Code!!


  • 0
    A
            if len(nums)==0:
                return []
            uniqueElem = []
            nums.sort()
            for i in range(len(nums)):
                for j in range(i+1,len(nums)):
                    num1 = nums[i]
                    num2 = nums[j]
                    left = j+1
                    right = len(nums)-1
                    while left<right:
                        sum = num1+num2+nums[left]+nums[right]
                        temp = [num1,num2,nums[left],nums[right]]
                        temp.sort()
                        if sum==target:
                            if temp not in uniqueElem:
                                uniqueElem.append(temp)
                            right -= 1
                            left += 1
                        elif sum>target:
                            right -= 1
                        else:
                            left += 1
            return uniqueElem

  • 0
    X

    Is it because you didnt' sort in the beginning? Because then you will have to do
    "if temp not in uniqueElem: ..."
    as you did. I guess this will cost you O(log(n)), so your time cost would become O (n^3 log(n)).


Log in to reply
 

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