leetcode 160. Intersection of Two Linked Lists python
题目
Write a program to find the node at which the intersection of two singly linked lists begins.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
解法1:brutal force
**首先理解题意指的是node所在的物理位置相同才代表是同一个节点,而不是单纯的节点value相同,看Example1就可以明白了。**采用双层循环的方法,TLE了
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
tmp2 = headB
while tmp2:
tmp1 = headA
while tmp1:
if tmp1 == tmp2:
return tmp1
tmp1 = tmp1.next
tmp2 = tmp2.next
return None
时间复杂度:O(mn)
空间复杂度:O(1)
解法2:使用栈
利用intersection node之后的所有node都相同的特性&#x