zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 7

    Intersection of Two Linked Lists

    要点:超有B格的写法:同步移动指针A和B,如果其中任何一个为空了,redirect到另一个。如果中间有重叠说明是交汇的。原理就是无论在哪个结点相交,两个指针最终保证走的距离是相等的。起始位置距离相交点的差别被补齐了。
    pattern:如果最终两次移动都失败了,那么最终任意一个指针为空,说明没有相交。同时要用bool记录是否已经完结过一次了。
    错误点:

    • 如果不用在循环内返回None,对大输入会莫名其妙有Memory Limit Exceeded错误
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def getIntersectionNode(self, headA, headB):
            """
            :type head1, head1: ListNode
            :rtype: ListNode
            """
            curA = headA
            curB = headB
            endA = False
            endB = False
            while curA and curB:
                if curA==curB: return curA
                curA = curA.next
                curB = curB.next
                if not curA and not endA:
                    curA = headB
                    endA = True
                
                if not curB and not endB:
                    curB = headA
                    endB = True
            
            return None
    
    
  • 相关阅读:
    寒假 学习进度七
    寒假学习进度
    寒假学习进度五
    寒假学习进度四
    寒假学习进度三
    寒假学习进度二
    Spark实验五
    半篇论文笔记
    REPL
    Scala基本语法及操作、程序控制结构
  • 原文地址:https://www.cnblogs.com/absolute/p/5582682.html
Copyright © 2011-2022 走看看