LeetCode 面试题 02.07. 链表相交

题目:

https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/

题解一:

哈希表。先将链表A中的的节点都放入哈希表,然后依次放入链表B中的节点,如果当前节点在哈希表中已存在证明链表相交。时间复杂度:O(N)

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> existNodeSet = new HashSet<>(100);
        ListNode tempA = headA;
        ListNode tempB = headB;

        while (tempA != null) {
            existNodeSet.add(tempA);
            tempA = tempA.next;
        }

        while (tempB != null) {
            if (existNodeSet.contains(tempB)) {
                return tempB;
            }

            tempB = tempB.next;
        }

        return null;
    }

题解二:

双指针法。

1.先遍历链表获取链表的长度lengthA,lengthB。

2.链表长度大的先走|lenthA-lengthB|。

3.现在两个指针处于同一起跑线,同时向后遍历,如果当前节点相等即相交。

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode tempA = headA;
        ListNode tempB = headB;

        int lengthA = 0;
        int lengthB = 0;

        while (tempA != null) {
            tempA = tempA.next;
            lengthA++;
        }

        while (tempB != null) {
            tempB = tempB.next;
            lengthB++;
        }

        int gap = Math.abs(lengthA - lengthB);
        tempA = headA;
        tempB = headB;

        if (lengthA > lengthB) {
            while (gap-- > 0) {
                tempA = tempA.next;
            }
        } else {
            while (gap-- > 0) {
                tempB = tempB.next;
            }
        }

        while (tempA != null) {
            if (tempA == tempB) {
                return tempA;
            }

            tempA = tempA.next;
            tempB = tempB.next;
        }

        return null;
    }

时间复杂度:O(N)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值