LeetCode--Intersection of Two Linked Lists (两个链表的交点)Python

来源:互联网 发布:helloworld的java程序 编辑:程序博客网 时间:2024/05/19 21:19

题目:

给定两个链表,求这两个链表的交点。若没有交点,则返回空。样例如下(返回交点c1):

解题思路:

思路1:暴力思路,n方复杂度。对两个链表分别进行遍历,找到相同的节点即可O(n*m),空间复杂度为O(1)。

思路2:使用哈希表,即python中的字典。先遍历一个链表,并将链表内容放入字典。再遍历另外一个链表,看遍历到的位置是否存在于字典中,存在则返回当前结点。若遍历结束仍不存在则返回空。检索复杂度为O(m+n),空间复杂度O(m+n)

思路3:先分别计算两个链表的长度。先读较长的链表,读到两个链表等长的时候再同时读两个链表,并判断两个链表遍历到的当前节点是否相同。检索复杂度为O(m+n),空间复杂度为O(1)

代码(Python,思路3):

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def getIntersectionNode(self, headA, headB):        """        :type head1, head1: ListNode        :rtype: ListNode        """        if headA==None or headB==None:            return None                def readLen(head):            count = 0            while(head):                if head==None:                    return count                else:                    head = head.next                    count = count+1            return count        len_A = readLen(headA)        len_B = readLen(headB)                if len_A >= len_B:            for i in range(len_A-len_B):                headA = headA.next        else:            for i in range(len_B-len_A):                headB = headB.next                        min_len = min(len_A,len_B)        for i in range(min_len):            if headA==headB:                return headA            else:                headA = headA.next                headB = headB.next        return None


附求助:

有哪位大佬知道这个题目在用leetcode的编辑器时找不到“runcode”按钮的原因?刷这个题目只能盲交,都没有在线测试TT 跪求原因!

阅读全文
0 0
原创粉丝点击