From 1aab307ed7a0e9c539bc450fdf7fbdc3082a1b67 Mon Sep 17 00:00:00 2001 From: Eyjan_Huang <81480748+Eyjan-Huang@users.noreply.github.com> Date: Sat, 14 Aug 2021 23:18:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20=E9=9D=A2=E8=AF=95?= =?UTF-8?q?=E9=A2=9802.07=20=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4python?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用更简单的逻辑完成这道题。 --- problems/面试题02.07.链表相交.md | 37 ++++++++----------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 9acda71c..8c3a5831 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -160,34 +160,21 @@ Python: class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: - lengthA,lengthB = 0,0 - curA,curB = headA,headB - while(curA!=None): #求链表A的长度 - curA = curA.next - lengthA +=1 - - while(curB!=None): #求链表B的长度 - curB = curB.next - lengthB +=1 - - curA, curB = headA, headB + """ + 根据快慢法则,走的快的一定会追上走得慢的。 + 在这道题里,有的链表短,他走完了就去走另一条链表,我们可以理解为走的快的指针。 - if lengthB>lengthA: #让curA为最长链表的头,lenA为其长度 - lengthA, lengthB = lengthB, lengthA - curA, curB = curB, curA + 那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个 + 位置相遇 + """ + cur_a, cur_b = headA, headB # 用两个指针代替a和b - gap = lengthA - lengthB #求长度差 - while(gap!=0): - curA = curA.next #让curA和curB在同一起点上 - gap -= 1 - while(curA!=None): - if curA == curB: - return curA - else: - curA = curA.next - curB = curB.next - return None + while cur_a != cur_b: + cur_a = cur_a.next if cur_a else headB # 如果a走完了,那么就切换到b走 + cur_b = cur_b.next if cur_b else headA # 同理,b走完了就切换到a + + return cur_a ``` Go: