My code works, but not efficient, can someone advice?


  • 0
    L

    Due to lack of efficiency, I cannot pass all the tests. I tried, but can hardly improve further. Can someone help?

    Below is my code:

    import copy
    class Solution(object):
    def threeSum(self, nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    nums=sorted(nums)
    Result=[]

    Dict={}

        Record1and2and3=[]
    

    nums=list(set(nums))

    print(nums)

        for i in range(len(nums)):
            nums2=copy.deepcopy(nums[i+1:])
    

    nums2.pop(i)

    print(nums[i],nums2)

            for j in range(len(nums2)):
                sum1and2=nums[i]+nums2[j]
    

    print("Sum2",sum2List)

    nums3=copy.deepcopy(nums2[j+1:])

                nums3=copy.deepcopy(nums)
    

    print(nums[i],nums2[j])

                nums3.remove(nums[i])
                nums3.remove(nums2[j])
                nums1and2and3=[]
                nums1and3=[]
                nums1and2and3=[nums[i],nums2[j],-sum1and2]
    

    print("nums1and2and3",nums1and2and3)

                if -4 in nums1and2and3 :
                    pass
                Sorted1and2and3=sorted(nums1and2and3)
    

    if Sorted1and2and3[0]==-4 and Sorted1and2and3[1]==0:

    pass

    print(sorted(nums1and2and3))

                if Sorted1and2and3 not in Record1and2and3:
                    Record1and2and3.append(Sorted1and2and3)
                else:
                    continue
    

    nums1and3=[nums[i],-sum1and2]

                if (-sum1and2) in nums3:
                    Result.append(Sorted1and2and3) 
    

    print("Record1and2and3",Record1and2and3)

        return Result
    

    print(Solution().threeSum([-1, 0, 1, 2, -1, -4]))

    print(Solution().threeSum([-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6]))>! >! >! >! Spoilerrint(Solution().threeSum([-13,5,13,12,-2,-11,-1,12,-3,0,-3,-7,-7,-5,-3,-15,-2,14,14,13,6,-11,-11,5,-15,-14,5,-5,-2,0,3,-8,-10,-7,11,-5,-10,-5,-7,-6,2,5,3,2,7,7,3,-10,-2,2,-12,-11,-1,14,10,-9,-15,-8,-7,-9,7,3,-2,5,11,-13,-15,8,-3,-7,-12,7,5,-2,-6,-3,-10,4,2,-5,14,-3,-1,-10,-3,-14,-4,-3,-7,-4,3,8,14,9,-2,10,11,-10,-4,-15,-9,-1,-1,3,4,1,8,1]))


Log in to reply
 

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