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
- LeetCode--Intersection of Two Linked Lists (两个链表的交点)Python
- LeetCode OJ 之 Intersection of Two Linked Lists (两个链表的交点)
- 160 Intersection of Two Linked Lists 求两个链表的交点
- 【leetcode 两个链表的交集点】Intersection of Two Linked Lists
- 【leetcode 两个链表的交集点】Intersection of Two Linked Lists
- [leetcode]Intersection of Two Linked Lists[java]找出两个链表的公共节点
- (LeetCode)Intersection of Two Linked Lists --- 两个链表的交集
- Leetcode-Intersection of Two Linked Lists-Python
- leetcode解题之160# Intersection of Two Linked Lists Java版 (两个链表的第一个公共结点)
- 【leetcode】160. Intersection of Two Linked Lists(Python & C++)
- Intersection of Two Linked Lists 找出2个链表的交点
- 160. Intersection of Two Linked Lists (求两个链表的交集)
- 380.Intersection of Two Linked Lists-两个链表的交叉(中等题)
- LeetCode---(160)Intersection of Two Linked Lists判断两个链表是否相交
- LeetCode—Intersection of Two Linked Lists 找两个链表的相交位置,让长的链表先走一段
- LeetCode 160 Intersection of Two Linked Lists(链表相交)(Linked List)(*)
- [Lintcode]Intersection of Two Linked Lists 两个链表的交叉
- [leetcode]Intersection of Two Linked Lists —— 熟悉python
- Activity任务栈和启动模式
- Android EditText无法换行
- 京东mate10评论分析
- spring Security4 和 oauth2整合 注解+xml混合使用(进阶篇)
- 最简单的spring架构
- LeetCode--Intersection of Two Linked Lists (两个链表的交点)Python
- 指针与数组_数组指针
- 网站导出20171201
- 读书04《番茄工作法图解下》
- 一些好的网站记录(PART 8)
- 搭建IPv6网络环境
- 机器学习-第四周作业——构建深度神经网络
- React学习笔记_ReactRedux应用使用AsyncAwait
- dubbo 常见错误