Leetcode之Intersection of Two Linked Lists
来源:互联网 发布:上海游安网络 编辑:程序博客网 时间:2024/05/24 04:30
给定两个链表,找出交集点,要求时间复杂度是O(n)、空间复杂度为O(1)
- 暴力破解:遍历链表A的所有节点,并且对于每个节点,都与链表B中的所有节点比较,退出条件是在B中找到第一个相等的节点。时间复杂度为O(lengthA * lengthB),空间复杂度为O(1)
- 哈希表方法:遍历链表A,并且将节点存储到哈希表中。接着遍历链表B,对于B中的每个节点,查找哈希表,如果在哈希表中找到了,说明是交集开始的那个节点。时间复杂度为O(lengthA + lengthB), 空间复杂度为(lengthA)
- 双指针法:指针pa、pb分别指向链表A和B的首节点。遍历链表A,记录其长度lengthA,遍历链表B,记录其长度lengthB。因为两个链表的长度可能不相同,比如题目所给的case,lengthA=5,lengthB=6,则作差得到 lengthB- lengthA=1,将指针pb从链表B的首节点开始走1步,即指向了第二个节点,pa指向链表A首节点,然后它们同时走,每次都走一步,当它们相等时,就是交集的节点。时间复杂度O(lengthA+lengthB),空间复杂度O(1)。双指针法代码:
# 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 """ length_a = 0 length_b = 0 copy_headA = headA copy_headB = headB while copy_headA != None: length_a += 1 copy_headA = copy_headA.next while copy_headB != None: length_b += 1 copy_headB = copy_headB.next diff = abs(length_a - length_b) if length_a > length_b: while diff > 0: headA = headA.next diff -= 1 if length_b > length_a: while diff > 0: headB = headB.next diff -= 1 while headA != None: if headA == headB: return headA headA = headA.next headB = headB.next return None
0 0
- leetcode之Intersection of Two Linked Lists
- LeetCode之Intersection of Two Linked Lists
- LeetCode 之 Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- Leetcode之Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- Leetcode 之 Intersection of Two Linked Lists
- [leetcode] [leetcode]Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode: Intersection of Two Linked Lists
- [Leetcode] Intersection of Two Linked Lists
- [Leetcode]Intersection of Two Linked Lists
- LeetCode:Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- Leetcode: Intersection of Two Linked Lists
- Intersection of Two Linked Lists--leetcode
- [leetcode]Intersection of Two Linked Lists
- <string.h>
- Java语言类库中几个常用的包
- poj1611 并查集
- 关于大型网站技术演进的思考(五)--存储的瓶颈(5)
- 为设置最顶层LinearLayout的width和height会导致:运行时,程序无反应,并显示“已停止”
- Leetcode之Intersection of Two Linked Lists
- Git使用笔记01
- tkinter 奇妙的突然无法修改Text对象问题
- linux中使用svn客户端
- ZeroMQ+VS2010配置
- Android内存泄漏的各种原因详解
- 搭建Maven私服
- Linux下用C语言实现ls -l的功能
- activity的启动方式 requestCode和resultCode的区别