LeetCode - Intersection of Two Linked Lists
来源:互联网 发布:林黛玉漂亮吗 知乎 编辑:程序博客网 时间:2024/06/17 14:48
https://leetcode.com/problems/intersection-of-two-linked-lists/
这道题一开始我想用hashtable做,就是先遍历第一个list,把node都放到hashset里面,然后遍历第二个,如果hashset里面有某个node,就说明这是intersection。
后来发现要求O(1) space,这样的话,先算两个list的长度,然后比较长的那个List先走两个长度的差那么多步,然后两个list再一起往前走,直到走到相同的node或者两个都为null为止。如果两个都为null,说明没有Intersection,不过在代码中不需要额外的分支来处理这个问题了,因为两个都是null也能相等,直接返回null就可以了。
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA ==null || headB == null) return null; ListNode tvs1 = headA; int len1 = 0; ListNode tvs2 = headB; int len2 = 0; while(tvs1 != null){ tvs1 = tvs1.next; len1++; } while(tvs2 != null){ tvs2 = tvs2.next; len2++; } int dif = Math.abs(len1-len2); if(len1>=len2){ tvs1 = headA; tvs2 = headB; } else{ tvs1 = headB; tvs2 = headA; } while(dif>0){ tvs1 = tvs1.next; dif--; } while(tvs1 != tvs2){ tvs1 = tvs1.next; tvs2 = tvs2.next; } return tvs1; }}
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
- 没备份的情况下,误删除数据文件的恢复
- 杭电 HDU ACM 圆桌会议
- FFmpeg常用基本命令
- Unity Mathf 数学运算(C#)
- 如何封装RESTful Web Service
- LeetCode - Intersection of Two Linked Lists
- poj 3911 Internet Service Providers 解一元二次方程
- MySQL触发器Trigger实例篇
- 并行程序设计导论 第三章习题
- 学习笔记(4):状态机与动画结合
- 自定义数组,实现输出改数组的长度、最大值和最小值
- java中不同的数据类型传值到方法中,会产生什么影响
- spline和Pchips的不同(matlab)
- 2015-4-2C语言学习日记