当前位置:网站首页>leetcode/两个链表的第一个重合节点
leetcode/两个链表的第一个重合节点
2022-08-10 11:36:00 【xcrj】
代码
package com.xcrj;
import java.util.HashSet;
import java.util.Set;
/** * 剑指 Offer II 023. 两个链表的第一个重合节点 * 给定两个单链表的头节点 headA 和 headB ,请找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。 */
public class Solution23 {
/** * 散列法 * 先统计headA于set中,再逐个遍历headB判断set中是否包含某个结点 */
public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
Set<ListNode> aSet = new HashSet<>();
ListNode pa = headA;
while (pa != null) {
aSet.add(pa);
pa = pa.next;
}
ListNode pb = headB;
while (pb != null) {
if (aSet.contains(pb)) {
return pb;
}
pb = pb.next;
}
return null;
}
/** * 双指针,指针交叉,速度相同的双指针要想相遇需要从同样的起点出发 * * 若 a长度等于b,pa pb指针速度一致 不用遍历c就能相遇 * 若 a长度大于b,pb走完自己的链表(b+c)时,pa也走了长度(b+c)还剩余a-b没走,此时让pb也走a-b。pa和pb都走完a-b后二者就走到了同样的起点往前走 */
public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
// 特殊情况处理
if (null == headA || null == headB) {
return null;
}
// 双指针
ListNode pa = headA;
ListNode pb = headB;
while (pa != pb) {
pa = pa == null ? headB : pa.next;
pb = pb == null ? headA : pb.next;
}
return pa;
}
public static void main(String[] args) {
}
}
参考
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/3u1WK4/solution/liang-ge-lian-biao-de-di-yi-ge-zhong-he-0msfg/
来源:力扣(LeetCode)
边栏推荐
- Threshold-based filtering buffer management scheme in a shared buffer packet switch core part of the paper
- 时间序列的数据分析(五):简单预测法
- Can CLIP also do segmentation tasks?The University of Göttingen proposed a model CLIPSeg that uses text and image prompts to perform three segmentation tasks at the same time, draining CLIP capabiliti
- LeetCode 61. Rotating linked list
- 厚积薄发!安全狗再次获得科技成果转化认证!
- 迈矽科推出高性能77GHz毫米波雷达芯片,尚未量产就已获数万颗订单
- 单目操作符(含原码反码补码转换)
- Buckle exercise - rectangular area does not exceed the maximum value of K and (hard)
- 配置druid数据源「建议收藏」
- HDU 4372:Count the Buildings (Stirling数)
猜你喜欢
可视化服务编排在金融APP中的实践
人脸考勤是选择人脸比对1:1还是人脸搜索1:N?
A case of violent parameter tuning in machine learning
A detailed explanation of implementation api embed
皕杰报表在传参乱码
You have a Doubaqiong thesaurus, please check it
APP automation testing practice based on UiAutomator2+PageObject mode
孩子自律性不够?猿辅导:计划表要注意“留白”给孩子更多掌控感
LT8911EXB MIPI CSI/DSI转EDP信号转换
一文读懂NFT数字藏品为何风靡全球?
随机推荐
dedecms supports one-click import of Word content
正则表达式常用示例
search--01
What are some useful performance testing tools recommended? Performance testing report charging standards
传三星3nm斩获第二家客户,目前产能已供不应求
态路小课堂丨如何为CXP光模块选择光纤跳线?
LeetCode 109. 有序链表转换二叉搜索树
可视化服务编排在金融APP中的实践
Centos7 environment uses Mysql offline installation package to install Mysql5.7
HDU 4372:Count the Buildings (Stirling数)
std::move()
苹果逆势扩大iPhone 14系列备货,总量或达9500万部
Threshold-based filtering buffer management scheme in a shared buffer packet switch core part of the paper
Diary 16
Analysis of the implementation principle of UUID from the perspective of source code
再有人问你分布式事务,把这篇扔给他
Excel function formulas - HLOOKUP function
你有一份斗破苍穹词库,请查收
2016,还是到了最后
LeetCode 369. Plus One Linked List