题目描述:输入两个链表,找出它们的第一个公共节点。
注意:
比较容易想到的思路:
map[节点]=true
代码实现如下:
// ac地址:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/
// 原文地址:https://xxoo521.com/2020-03-12-list-node/
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function(headA, headB) {
const map = new Map();
let node = headA;
while (node) {
map.set(node, true);
node = node.next;
}
node = headB;
while (node) {
if (map.has(node)) return node;
node = node.next;
}
return null;
};
时间复杂度是$O(N)$,空间复杂度是$O(N)$。
题目提示了,空间复杂度可以降低到$O(1)$。这时候不能用哈希表,可以使用快慢指针的思路来处理。整体思路如下:
代码实现是:
// ac地址:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/
// 原文地址:https://xxoo521.com/2020-03-12-list-node/
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function(headA, headB) {
let node = headA;
let lengthA = 0;
while (node) {
++lengthA;
node = node.next;
}
if (!lengthA) return null;
node = headB;
let lengthB = 0;
while (node) {
++lengthB;
node = node.next;
}
if (!lengthB) return null;
let diff = 0,
slow,
fast;
if (lengthA > lengthB) {
slow = headA;
fast = headB;
diff = lengthA - lengthB;
} else {
slow = headB;
fast = headA;
diff = lengthB - lengthA;
}
while (diff--) {
slow = slow.next;
}
while (slow !== fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
};
时间复杂度是$O(N)$,空间复杂度是$O(1)$。效果也蛮好的,时间击败 95.49%,内存击败 100%。截图如下: