update 面试题02.07.链表相交 python代码 js注释

This commit is contained in:
Yuhao Ju
2022-11-24 00:15:31 +08:00
committed by GitHub
parent af0e45b9af
commit d9950cee1b

View File

@ -155,23 +155,28 @@ public class Solution {
class Solution: class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
""" lenA, lenB = 0, 0
根据快慢法则,走的快的一定会追上走得慢的。 cur = headA
在这道题里,有的链表短,他走完了就去走另一条链表,我们可以理解为走的快的指针。 while cur: # 求链表A的长度
cur = cur.next
那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个 lenA += 1
位置相遇 cur = headB
""" while cur: # 求链表B的长度
if headA is None or headB is None: cur = cur.next
return None lenB += 1
cur_a, cur_b = headA, headB # 用两个指针代替a和b curA, curB = headA, headB
if lenA > lenB: # 让curB为最长链表的头lenB为其长度
curA, curB = curB, curA
while cur_a != cur_b: lenA, lenB = lenB, lenA
cur_a = cur_a.next if cur_a else headB # 如果a走完了那么就切换到b走 for _ in range(lenB - lenA): # 让curA和curB在同一起点上末尾位置对齐
cur_b = cur_b.next if cur_b else headA # 同理b走完了就切换到a curB = curB.next
while curA: # 遍历curA 和 curB遇到相同则直接返回
return cur_a if curA == curB:
return curA
else:
curA = curA.next
curB = curB.next
return None
``` ```
### Go ### Go
@ -248,19 +253,21 @@ var getListLen = function(head) {
} }
var getIntersectionNode = function(headA, headB) { var getIntersectionNode = function(headA, headB) {
let curA = headA,curB = headB, let curA = headA,curB = headB,
lenA = getListLen(headA), lenA = getListLen(headA), // 求链表A的长度
lenB = getListLen(headB); lenB = getListLen(headB);
if(lenA < lenB) { if(lenA < lenB) { // 让curA为最长链表的头lenA为其长度
// 下面交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时
// 交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时
// 如果不加分号,下面两条代码等同于一条代码: [curA, curB] = [lenB, lenA] // 如果不加分号,下面两条代码等同于一条代码: [curA, curB] = [lenB, lenA]
[curA, curB] = [curB, curA]; [curA, curB] = [curB, curA];
[lenA, lenB] = [lenB, lenA]; [lenA, lenB] = [lenB, lenA];
} }
let i = lenA - lenB; let i = lenA - lenB; // 求长度差
while(i-- > 0) { while(i-- > 0) { // 让curA和curB在同一起点上末尾位置对齐
curA = curA.next; curA = curA.next;
} }
while(curA && curA !== curB) { while(curA && curA !== curB) { // 遍历curA 和 curB遇到相同则直接返回
curA = curA.next; curA = curA.next;
curB = curB.next; curB = curB.next;
} }