力扣双指针
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
a,b=headA,headB
while a!=b:
if a==None:
a=headB
else:
a=a.next
if b==None:
b=headA
else:
b=b.next
return a
我的做法:暴力破解时间复杂度不符合题目要求
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
a,b=headA,headB
while a:
while b:
if a == b:
return b
else:
b=b.next
a=a.next
return None
总结
1.我自己第一想法只能想到时间复杂度比较高的解法,关键今天我这个想法还得不出正确答案,在网上搜索了一番,大多数我这个想法的都没写代码,不知道哪里出了问题,我没耐心了,换个科目,明天再继续研究我的问题。
2.每次看到力扣的解题思路,都觉得恍然大悟,为什么别人可以想出来,不过,没关系,我要乐观点,做多了,我也可以,加油。
11.9号更新
终于用我的解法做出来了,之前是由于 b=headB这句写在了错误的地方,导致第一轮循环后b一直指向了None,正确的解法如下。
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
a=headA
while a:
b=headB
while b:
if a == b:
return b
else:
b=b.next
a=a.next
return None