LeetCode - Intersection of Two Linked Lists
2015-04-03 01:05
357 查看
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就可以了。
这道题一开始我想用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; } }
相关文章推荐
- [LeetCode]Intersection of Two Linked Lists
- 【leetcode 两个链表的交集点】Intersection of Two Linked Lists
- Leetcode_160_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 in JAVA
- [Leetcode]Intersection of Two Linked Lists
- [Leetcode] Intersection of Two Linked Lists
- [leetcode]Intersection of Two Linked Lists —— 熟悉python
- 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