LeetCode:Intersection of Two Linked Lists
2014-11-28 23:09
429 查看
时间复杂度O(N+M),空间复杂度O(1):
第一遍遍历两个列表,得到列表headA和headB的元素个数N,M,假设N>M。
然后headA从第N-M个元素开始遍历,headB从第一个元素开始遍历,遇到相等的元素返回。如果遍历到末尾都不相等,返回NULL。
与标准答案的复杂度是一样的,我的方法更好理解些。
第一遍遍历两个列表,得到列表headA和headB的元素个数N,M,假设N>M。
然后headA从第N-M个元素开始遍历,headB从第一个元素开始遍历,遇到相等的元素返回。如果遍历到末尾都不相等,返回NULL。
与标准答案的复杂度是一样的,我的方法更好理解些。
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int lenA = getLen(headA); int lenB = getLen(headB); ListNode shortHead = headA; ListNode longHead = headB; if (lenA > lenB) { shortHead = headB; longHead = headA; } int i = 0; while (i < Math.abs(lenB - lenA)) { i++; longHead = longHead.next; } while (shortHead != longHead) { shortHead = shortHead.next; longHead = longHead.next; if (shortHead == null) { return null; } } return shortHead; } private int getLen(ListNode head) { int len = 0; while (head != null) { len++; head = head.next; } return len; } }
相关文章推荐
- 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
- Intersection of Two Linked Lists--leetcode
- 【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
- LeetCode 160 — Intersection of Two Linked Lists(C++ 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_160_Intersection of Two Linked Lists