• OJ练习32——T160 Intersection of Two Linked Lists


    找两个链表的交叉节点,像这样:

    A:            a1 → a2
                               ↘
                            c1 → c2 → c3
                           ↗            
    B:     b1 → b2 → b3

    没有交叉返回null;

    第一个相同的节点就是交叉开始的地方(经验证,该题系统是这样,见后)

    【思路】

    1.从后向前遍历,遇到第一个不相同的就停止,但是链表不支持逆序,drop。

    2.从哪个节点开始比较呢?先遍历一次,得到两个链表的长度,长度差为0的地方开始比。

    【my code】

    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *a,*b,*re;
        a=headA;
        b=headB;
        int la=0,lb=0;
        while(a!=NULL){
            a=a->next;
            la++;
        }
        while(b!=NULL){
            b=b->next;
            lb++;
        }
        a=headA;
        b=headB;
        while(lb>la){
            b=b->next;
            lb--;
        }
        while(la>lb){
            a=a->next;
            la--;
        }
        while(a!=NULL&&b!=NULL){
            if(a->val!=b->val){
                a=a->next;
                b=b->next;
                continue;
            }
            else{
                re=a;
                while(a!=NULL&&b!=NULL&&a->val==b->val){//here
                    a=a->next;
                    b=b->next;
                }
                if(a==NULL&&b==NULL)
                    return re;
                else
                    continue;
            }
        }
        return NULL;
    }

    【评价】

    用时120ms,都不在cpp的时间范围里了!

    找了找原因,原来是我用了双层while,看了别人的答案不需要第二层,遇到的第一个相同的节点就是所求。

    去掉该while后,用时75ms,比较正常。

  • 相关阅读:
    PAT 甲题 1155 Heap Paths
    PAT甲题 1014 Waiting in Line
    PAT甲题 1014 Waiting in Line
    AcWing 840. 模拟散列表
    2019新生赛 %%%xxh
    AcWing 240. 食物链
    AcWing 143. 最大异或对
    AcWing 838. 堆排序
    AcWing 836. 合并集合
    AcWing 837. 连通块中点的数量
  • 原文地址:https://www.cnblogs.com/ketchups-notes/p/4460548.html
Copyright © 2020-2023  润新知