Why is my python solution always returning memory limit exceeded


  • 0
    W

    The same solution got passed in javascript. Anyone knows what's going on with python? Thought it'd be good to know if this is some kinda python nature.

    def getIntersectionNode(self, headA, headB):
            """
            :type head1, head1: ListNode
            :rtype: ListNode
            """
            if not headA or not headB:
                return None
            p1, p2 = headA, headB
            while p1 != p2:
                if not p1:
                    p1 = headB
                elif not p2:
                    p2 = headA
                else:
                    p1 = p1.next
                    p2 = p2.next
            return p1
    

  • 1
    W

    Hi,

    I got the same problem then solved it using gc.collect(), following shiyanhui's suggestion.
    https://discuss.leetcode.com/topic/60622/fixed-python-accepted-solution-before-now-causes-memory-limit-exceeded/2

    import gc
    
    class Solution(object):
        def getIntersectionNode(self, headA, headB):
            a, b = headA, headB
            while a is not b:
                a = headB if a is None else a.next
                b = headA if b is None else b.next
            # clean the memory
            gc.collect()
            return a
    

  • 0
    W

    @liwuyuana You got it! Thanks a lot!


Log in to reply
 

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