当前位置:网站首页>LeetCode刷题|两个链表的第一个公共节点
LeetCode刷题|两个链表的第一个公共节点
2022-04-23 05:58:00 【杜小瑞】
题目描述
题目地址:两个链表的第一个公共节点
解法一:暴力枚举
一个朴素的想法是直接对每一个节点进行枚举,这样做的时间复杂度是O(M*N)。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
for(ListNode pa = headA; pa!=null; pa = pa.next) {
for(ListNode pb = headB; pb!=null; pb = pb.next) {
if(pa==pb) {
return pa;
}
}
}
return null;
}
}
解法二:哈希集合
从一个头结点开始遍历一遍,将所有节点放入一个哈希集合中,再从另一个头结点开始遍历,遍历到第一个在哈希集合中的节点就是第一个相遇的节点。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<ListNode>();
ListNode temp = headA;
while(temp!=null) {
set.add(temp);
temp = temp.next;
}
while(headB!=null) {
if(set.contains(headB)) {
return headB;
}
headB = headB.next;
}
return null;
}
}
解法三:双指针
如果一开始两个指针都为空,直接返回空。
两个临时指针分别从两个头结点开始遍历,遍历到结尾后回到头结点继续往下,两个临时节点每一次共同更新一步,总有一天两个节点会相遇。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode pa=headA, pb=headB;
if(pa==null & pb==null) {
return null;
}
while(pa!=pb) {
pa = pa == null ? headA : pa.next;
pb = pb == null ? headB : pb.next;
}
return pa;
}
}
解法四:双栈
维护两个栈,将两个头结点遍历的元素分别加入两个栈中。然后开始同时出栈,直到同时出栈的元素不同,说明上一个出栈的元素是第一个公共节点。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode pa=headA, pb=headB;
Deque<ListNode> d1 = new ArrayDeque<ListNode>(), d2 = new ArrayDeque<ListNode>();
while(pa!=null) {
d1.add(pa);
pa = pa.next;
}
while(pb!=null) {
d2.add(pb);
pb = pb.next;
}
ListNode ans = null;
while(!d1.isEmpty() && !d2.isEmpty() && d1.peekLast()==d2.peekLast()) {
ans = d1.pollLast();
d2.pollLast();
}
return ans;
}
}
版权声明
本文为[杜小瑞]所创,转载请带上原文链接,感谢
https://blog.csdn.net/DXRfighting/article/details/118976383
边栏推荐
- AttributeError: ‘dict‘ object has no attribute ‘iteritems‘
- The time format is incorrect, and an error is reported when running the SQL file
- 深入理解控制反转和依赖注入
- freeCodeCamp----shape_calculator练习
- Binary sum of leetcode questions
- Get DOM element location information by offset and client
- JS handwriting compatibility event binding
- Leetcode刷题之实现strStr()
- 数据可视化百度地图进一步优化
- Database programming of node
猜你喜欢
随机推荐
模仿扇贝短文阅读页面
.NET跨平台原理(上篇)
Curry realization of function continuous call calculation and accumulation
.Net Core 下使用 Quartz —— 【3】作业和触发器之作业传参
【代码解析(6)】Communication-Efficient Learning of Deep Networks from Decentralized Data
TP6 的 each 遍历用法
Promise(二)
JS手写兼容性事件绑定
Batch modify / batch update the value of a field in the database
tp5 报错variable type error: array解决方法
AttributeError: ‘dict‘ object has no attribute ‘iteritems‘
WebAPI+Form表单上传文件
Parse PSD files and map them into components
1-3 组件与模块
1-2 NodeJS的特点
Concurrent optimization request
1-5 NodeJS CommonJs规范
el-cascader和el-select点击别处让下拉框消失
条形码与二维码的生成
Tensorflow&&Pytorch常见报错