题解 | #两个链表的第一个公共结点#

两个链表的第一个公共结点

http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
#
class Solution:
    def FindFirstCommonNode(self , pHead1 , pHead2 ):
        # write code here
        s = self.helper(pHead1)
        cur = pHead2
        while cur:
            if cur in s: # 利用set集合进行判断 空间复杂度O(n)
                return cur
            cur = cur.next
        return None
    
    def helper(self,head):
        s = set()
        cur = head
        while cur:
            s.add(cur)
            cur = cur.next
        return s
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务