LeetCode:Intersection of Two Linked Lists
来源:互联网 发布:上古卷轴5原始捏脸数据 编辑:程序博客网 时间:2024/05/17 23:15
时间复杂度O(N+M),空间复杂度O(1):
第一遍遍历两个列表,得到列表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;}}
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
- 最长上升子序列nlogn算法
- 我理解的SharedPreferences
- MySQL中InnoDB和MyISAM两种表类型的区别
- vsftpd学习笔记二
- 关于未来规划
- LeetCode:Intersection of Two Linked Lists
- make的使用和Makefile的编写1
- C++中new与delete的用法
- 使用渐进式JPEG来提升用户体验
- GeoHash核心原理解析
- QuickSort 和 QuickSelection中partition注记
- 机器学习中的范数规则化之(一)L0、L1与L2范数
- jQuery学习之选择器
- 抽象类和接口的区别