leetcode: Intersection of Two Linked Lists
来源:互联网 发布:数据库程序设计考试 编辑:程序博客网 时间:2024/05/16 04:40
很久没做leetcode,更新了些新题做一下。
这题要求我们找到两个链表的公共部分,要求时间代价为O(n),空间代价为O(1)。
其实做法有很多种,比如先扫描一个链表,将其每个节点hash保存,再遍历第二个链表,判断每个节点是否在第一个链表中有出现。但这样空间复杂度为O(n),不符合要求。
我的做法如下:
显然,若两个链表存在公共节点,那么自公共节点之后两个链表的节点都是一样的;链表长度可能不一样,若我们将链表都限制在同样长度,那么从两端同时向next跳,当两端节点一样时即找到了公共节点,这个过程是O(n)的。限制链表长度可以实现便利两个链表获取各自的长度,将较长的那个向next跳 |lenA-lenB| 次以保证两个链表长度一致。这个过程也是O(n)的。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int lenA=0,lenB=0; ListNode stA = headA,stB = headB; while(stA!=null) { lenA++; stA = stA.next; } while(stB!=null) { lenB++; stB = stB.next; } if(lenA>lenB) { for(int i=1;i<=lenA-lenB;i++) { headA = headA.next; } } else if(lenB>lenA) { for(int i=1;i<=lenB-lenA;i++) { headB = headB.next; } } while(headA!=null&&headB!=null) { if(headA==headB) { return headA; } headA = headA.next; headB = headB.next; } return null; }}
看了下网上的解答,发现了更好的做法。虽然我的解法也符合要求,但实际上要遍历两遍链表。我们假设链表的公共部分为C,第一个链表自己的部分为A,第二个链表自己的部分为B,那么第一个链表为A+C,第二个链表为B+C。
由于两个链表长度不一,我们不妨扩展一下将其串起来(链表一后接一个链表二,链表二后接一个链表一)
此时链表一为A+C+B+C,链表二为B+C+A+C;
我们发现此时,链表一和链表二前三组都为A+C+B(不重复),那么同时开始遍历完这么多个节点之后,链表一和链表二将同时访问C,即为所求的公共节点起始;返回即可
0 0
- [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
- 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
- Java对象的强、软、弱和虚引用原理+结合ReferenceQueue对象构造Java对象的高速缓存器
- “Non Zero Exit Status” R 3.0.1 'XML' and 'RCurl'
- RS232与RS485的功能与区别!
- c#IO文件读写操作
- 实时操作系统
- leetcode: Intersection of Two Linked Lists
- adb wifi 调试不能连接解决
- IOS基本控件常用属性及方法(一)---UILabel
- cygwin常用命令
- storm文档(12)----自己搭建storm集群
- [译转]为开发人员提供的五种错误报告工具
- Ubuntu下搭建Django平台
- (转载)CCTMXTiledMap使用的几个事项
- 深入java--类型信息(反射)