打卡-相交链表

KL160相交链表

方法一:

红色是相交部分,找到长度差的地方,两个指针同时向后找即可。

时间复杂度:O(m+n+n)

空间复杂度:O(1)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5tBJNSiP-1651203153209)(D:\学习\截图\image-20220429110142890.png)]

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        if (headA == null || headB == null) {
            return null;
        }
        ListNode p1 = headA;
        ListNode p2 = headB;
        int n1 = 1, n2 = 1;
        while (p1 != null) {
            p1 = p1.next;
            n1++;
        }
        while (p2 != null) {
            p2 = p2.next;
            n2++;
        }
        int n3 = Math.abs(n1 - n2);
        p1 = headA;
        p2 = headB;
        if (n1 >= n2) {
            for (int i = 0; i < n3; i++) {
                p1 = p1.next;
            }
            while (p1 != null) {
                if (p1 == p2) {
                    return p1;
                }
                p1 = p1.next;
                p2 = p2.next;
            }
            return null;
        } else {
            for (int i = 0; i < n3; i++) {
                p2 = p2.next;
            }
            while (p1 != null) {
                if (p1 == p2) {
                    return p1;
                }
                p1 = p1.next;
                p2 = p2.next;
            }
            return null;
        }
    }
}

方法二:

方法1就是类似方法2,只不过不用提前移动指针,只需要交替遍历一次就可以保证两个数组步调一致了

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xDsLRjdR-1651203153210)(D:\学习\截图\image-20220429111852712.png)]

指针1开始走的:a+c+b

指针2开始走的:b+c+a

他们走的次数一样,而且都到了红色部分。如果相交,已经找到了。

时间复杂度:O(m+n) 比方法一稍微快了一点

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode pA = headA, pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值