【简单】面试题 02.07. 链表相交

643 篇文章 5 订阅

【题目】
给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用,而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点(引用完全相同),则这两个链表相交。
来源:leetcode
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
【代码】
执行用时 :52 ms, 在所有 C++ 提交中击败了90.58% 的用户
内存消耗 :14.6 MB, 在所有 C++ 提交中击败了100.00%的用户

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int callen(ListNode* listnode){
        int cnt=0;
        while(listnode){
            listnode=listnode->next;
            cnt++;
        }
        return cnt;
    }
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *shortlist=headA,*longlist=headB,*listnode;
        if(!headA||!headB)
            return NULL;
        int lenA=callen(shortlist),lenB=callen(longlist);
        int diff=lenB-lenA;
        if(lenA>lenB){
            swap(shortlist,longlist);
            diff=abs(diff);
        }
        while(diff--){
            longlist=longlist->next;
        }
        while(shortlist){
            if(shortlist==longlist)
                break;
            shortlist=shortlist->next;
            longlist=longlist->next;
        }
        return shortlist;
    }
};

【set】时间复杂度高相比上一个代码简洁
执行用时 :144 ms, 在所有 C++ 提交中击败了8.22% 的用户
内存消耗 :21.4 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
    set<ListNode*> s;
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        
        while(headA){
            s.insert(headA);
            headA=headA->next;
        }
        while(headB){
            if(s.count(headB))
                return headB;
            s.insert(headB);
            headB=headB->next;
        }
        return NULL;
    }
};

【双指针大法】虽然设计思想很巧妙,但是性能堪忧。不过比set法性能高一点。
执行用时 :72 ms, 在所有 C++ 提交中击败了36.25% 的用户
内存消耗 :14.4 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        
        ListNode* nodeA=headA,*nodeB=headB; 
        while(nodeA!=nodeB){
            if(!nodeA)
                nodeA=headB;
            else
                nodeA=nodeA->next;
            if(!nodeB)
                nodeB=headA;
            else
                nodeB=nodeB->next;
        }
        return nodeA;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值