[LeetCode]160. Intersection of Two Linked Lists
来源:互联网 发布:正交矩阵和实对称矩阵 编辑:程序博客网 时间:2024/04/27 15:14
原题链接:https://leetcode.com/problems/contains-duplicate-iii/
这道题目是easy题,所以会有可能出现在电面里面。思路也很简单,设置2个指针分别指向2个链表,如果链表长度不相等,假设2个链表相差k个节点,则我们让长度长的那个链表对应的指针先走前进k个节点,然后两个指针一起走,直走到2个指针指向相同的节点为止。时间复杂度是O(n)
代码如下:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null) return null; int lenA = 0; ListNode pA = headA; int lenB = 0; ListNode pB = headB; while(pA!=null) { lenA++; pA = pA.next; } while(pB!=null) { lenB++; pB = pB.next; } int diff = Math.abs(lenA-lenB); pA = headA; pB = headB; if(lenA>lenB) { while(diff>0 && pA!=null) { pA = pA.next; diff--; } } else if(lenA<lenB) { while(diff>0 && pB!=null) { pB = pB.next; diff--; } } while(pA!=null && pB!=null) { if(pA == pB) return pA; pA = pA.next; pB = pB.next; } return null; }
0 0
- [LeetCode]160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160.Intersection of Two Linked Lists
- [leetcode] 160.Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode *** 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode-160. Intersection of Two Linked Lists
- LeetCode-160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode 160. Intersection of Two Linked Lists
- 160.[Leetcode]Intersection of Two Linked Lists
- 内联函数详解(未完成)
- 浏览器cannot read property 'msie' of undefined的解决方法
- [LeetCode]159. Longest Substring with At Most Two Distinct Characters
- 图解正向代理、反向代理、透明代理
- 蓝桥杯 历届试题 蚂蚁感冒 (模拟)
- [LeetCode]160. Intersection of Two Linked Lists
- HDU 1004 Let the Balloon Rise(map)
- 短作业优先与时间片轮转法
- 一次失败的j2v8集成
- Tuple and Tie
- cmd运行Java程序的问题
- LeetCode78. Subsets
- 学习笔记-----listview中含有togglebutton
- 最简单的基于FFMPEG的转码程序