《剑指offer》刷题——【时间效率与空间效率的平衡】面试题52:两个链表的第一个公共结点(java实现)

《剑指offer》刷题——【时间效率与空间效率的平衡】面试题52:两个链表的第一个公共结点(java实现)

一、题目描述

输入两个链表,找出它们的第一个公共结点。

二、题目分析

方法一:双循环,O(n^2)

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
         //如果存在空链表,说明没有公共结点
        if(pHead1 == null || pHead2 == null){
            return null;
        }
        //以链表pHead1作为基本链表,取一个结点pHead2中的结点与之比较
        ListNode target = pHead1;
        
        while(target != null){
            ListNode cur = pHead2;//j将链表2头结点赋给新结点,避免直接修改pHead2
            while(cur != null){
                //如果链表1中结点与链表2中结点相等,则返回当前结点
                if(target == cur){
                    return target;
                }
                //否则链表2指针后移
                cur = cur.next;
            }
            //链表1指针后移
            target = target.next;
        }
        return null;
    }
}

方法二:Hash法

  • 将第二个链表存入HashMap中

  • 遍历第一个链表,判断该节点是否存在与HashMap,找出第一个存在与HashMap中的结点

  • 时间复杂度:O(m+n)

  • 空间复杂度:O(n)

import java.util.Map;
import java.util.HashMap;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
         //如果存在空链表,说明没有公共结点
        if(pHead1 == null || pHead2 == null){
            return null;
        }
        //将第二个链表存入HashMap中
        Map<ListNode, Integer> map = new HashMap<>();
        while(pHead2 != null){
            map.put(pHead2, 2);
            pHead2 = pHead2.next;
        }
        //遍历第一个链表,查找相同结点
        while(pHead1 != null){
            if(map.get(pHead1) != null){
                return pHead1;
            }
            pHead1 = pHead1.next;
        }
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值