面试笔试杂项积累-leetcode 156-160
来源:互联网 发布:海康提示网络不可达 编辑:程序博客网 时间:2024/05/20 21:47
160.160-Intersection of Two Linked Lists-Difficulty: Easy
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
思路
两个链表指向一个链表,找到汇聚的起点
解题思路:1.首先想到的是哈希,先将一个链表中结点都插入字典中,然后遍历另一个链表中的结点看是否有结点在字典中;但这种方法需要开辟较大的内存空间来存储字典;
2.双指针法.首先对其中一个链表头尾连接.那么问题就变成了看另一个链表是否存在环的问题了.但这种方法改变了原本链表的结构,需要在最后对其还原;
3.先计算两个链表的长度差,然后对长链表头结点开始移动长度差长的结点,找到位置对应的结点.然后逐个比较是否相等;
第二种方法就和之前的一道题一样,那就没有意义了博主选择了最机智的第三种方法
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */public class Solution { public ListNode GetIntersectionNode(ListNode headA, ListNode headB) { ListNode A_temp = headA; ListNode B_temp = headB; int A_Length = 0; int B_Length = 0; while (A_temp != null || B_temp != null) { if (A_temp != null) { ++A_Length; A_temp = A_temp.next; } if (B_temp != null) { ++B_Length; B_temp = B_temp.next; } } A_temp = headA; B_temp = headB; if (A_Length > B_Length) { for (int i = 0; i < A_Length - B_Length; i++) A_temp = A_temp.next; } else if (B_Length > A_Length) { for (int i = 0; i < B_Length - A_Length; i++) B_temp = B_temp.next; } while (A_temp != null) { if (A_temp == B_temp) return A_temp; A_temp = A_temp.next; B_temp = B_temp.next; } return null; }}
1 0
- 面试笔试杂项积累-leetcode 156-160
- 面试笔试杂项积累-leetcode 1-5
- 面试笔试杂项积累-leetcode 6-10
- 面试笔试杂项积累-leetcode 11-15
- 面试笔试杂项积累-leetcode 16-20
- 面试笔试杂项积累-leetcode 21-25
- 面试笔试杂项积累-leetcode 26-30
- 面试笔试杂项积累-leetcode 31-35
- 面试笔试杂项积累-leetcode 36-40
- 面试笔试杂项积累-leetcode 41-45
- 面试笔试杂项积累-leetcode 46-50
- 面试笔试杂项积累-leetcode 51-55
- 面试笔试杂项积累-leetcode 56-60
- 面试笔试杂项积累-leetcode 61-65
- 面试笔试杂项积累-leetcode 66-70
- 面试笔试杂项积累-leetcode 71-75
- 面试笔试杂项积累-leetcode 76-80
- 面试笔试杂项积累-leetcode 81-85
- zoj3471 Most Powerful(状态压缩dp)
- 面试笔试杂项积累-leetcode 151-155
- javascript计算器工作原理
- could not open parameter file '/u01/app/oracle/product/11.1.0/db_1/dbs/initorc11g.ora
- android数据存储的四种方案(三)
- 面试笔试杂项积累-leetcode 156-160
- POJ 1182_食物链
- 面试笔试杂项积累-leetcode 161-165
- 深夜学算法之SkipList:让链表飞
- POJ 2240_Arbitrage
- utf8解决JSP中文乱码问题
- linux习惯每天一个命令之mount命令
- Hibernate细节
- 今天是春节