Why my code get Memory Limit Exceed error? Please Help!


  • 0
    L
    class Solution:
    # @return a list of lists of length 3, [[val1,val2,val3]]
    def threeSum(self, num):
        num.sort()
        result = []
        for i in range(len(num)-2):
            if i > 0 and num[i]==num[i-1]:
                pass
            target = 0 - num[i]
            j = i + 1
            k = len(num)-1
            while j < k:
                ## check duplicate
                if (j > i + 1 and num[j]==num[j-1] )  or (k < len(num)-1 and num[k]==num[k+1]):
                        pass
                sum = num[j] + num[k]
                if sum == target:
                    result.append([num[i],num[j],num[k]])
                elif sum < target:
                    j += 1
                else:
                    k -= 1
                    
        return result

  • 0
    Y

    if sum == target:
    result.append([num[i],num[j],num[k]])

    Here is why you're infinitely looping, since you're not updating j and k in the case j=i+1 and k=num.size()-1 ia a valid case. You can either find a way (and yes you can) to incorporate this:

    if (j > i + 1 and num[j]==num[j-1] ) or (k < len(num)-1 and num[k]==num[k+1]):
    pass

    After appending the triplet. Or simple do j++, k-- after appending depending on your mood, which is also valid by considering exhaustive cases.


Log in to reply
 

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