两个链表的第一个公共节点 NC66

方法一:双指针

假设两个链表公共长度为C,不公共的长度分别为A、B。 则两个链表长度分别为A+C,B+C。 设两个指针,让第一个链表走完之后,跳到第二个链表开始走,共A+C+X1距离;同理第二个链表走完后调到第一个链表开始走,走B+C+X2距离。

那么两个指针相遇时,由 A+C+X1 = B+C+X2,距离不为负,得X1=B,X2=A,所以最后两个指针走的距离都是A+B+C,刚好在第一个公共点相遇。

复杂度分析

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

//双指针
var getIntersectionNode = function(headA, headB) {
    let node1 = headA, node2 = headB;
    while(node1 != node2) {
        node1 = node1 !== null ? node1.next : headB;
        node2 = node2 !== null ? node2.next : headA;
    }
    return node1;  //这里写node2结果也一样
};

 

方法二:Hashmap

第一个while循环遍历第一个链表,将其所有节点放入 map 中
第二个while遍历第二个链表,用 has 判断这个节点值是否存在第一个链表中。

  • has()方法: 判断Map对象中是否存在指定元素。如果具有指定元素则返回true,否则返回false。
  • set()方法: 为Map对象添加一个指定键(key)和值(value)的新元素。
  • get()方法: 用来获取一个 Map对象中指定的元素。
//hashmap法
var getIntersectionNode2 = function(headA, headB) {
    let map = new Map();
    while(headA) {
        map.set(headA, true);
        headA = headA.next;
    }
    while(headB) {
        if(map.has(headB)) //找到了第一个公共结点
            return headB;
        headB = headB.next;
    }
    return null;
};

ES6中增加了MapSet两种新的数据结构

  • Map是类似Object的一种键值对集合,区别在于Map的键不仅限于是字符串,其他各种类型的值包括对象都可以成为Map的键
  • Set是类似数组的一种数据结构,不同点在于Set中没有重复的值
### 找到两个链表第一个公共节点 #### 方法一:哈希集合 (基于引用[^1]) 通过使用 `Map` 或者 `Set` 数据结构来存储其中一个链表的所有节点。随后遍历另一个链表,检查当前节点是否已经存在于集合中。如果存在,则该节点即为两链表第一个公共节点。 这种方法的时间复杂度为 \(O(m+n)\),其中 \(m\) 和 \(n\) 是两条链表的长度;空间复杂度为 \(O(m)\) 或 \(O(n)\),取决于哪个链表被存入集合中。 ```python def getIntersectionNode(headA, headB): nodes_in_B = set() current_node = headB while current_node is not None: nodes_in_B.add(current_node) current_node = current_node.next current_node = headA while current_node is not None: if current_node in nodes_in_B: return current_node current_node = current_node.next return None ``` --- #### 方法二:双指针法 (基于引用[^2]) 定义两个指针分别指向两个链表头结点。每次移动一步,当到达链表末端时,跳转至另一条链表头部继续前进。这样可以消除两者之间的长度差,在第二次相遇处即是第一个公共节点。 此方法时间复杂度同样为 \(O(m+n)\),而空间复杂度降为了 \(O(1)\)。 ```python def getIntersectionNode(headA, headB): pointerA, pointerB = headA, headB while pointerA != pointerB: pointerA = headB if pointerA is None else pointerA.next pointerB = headA if pointerB is None else pointerB.next return pointerA # 返回值可能是公共节点或者None ``` --- #### 方法三:计算长度差异并调整起始位置 先遍历两条链表得到它们各自的长度,并求出差值。让较长的那个链表先行走这个差距步数后再同步逐一遍历比较各对应节点直至发现相等为止。 这种方式也实现了线性时间和常量级额外内存消耗的目标。 ```python def length(node): count = 0 while node: count += 1 node = node.next return count def getIntersectionNode(headA, headB): lenA, lenB = length(headA), length(headB) shorter = headA if lenA < lenB else headB longer = headB if lenA < lenB else headA diff = abs(lenA - lenB) for _ in range(diff): longer = longer.next while shorter and longer: if shorter == longer: return shorter shorter = shorter.next longer = longer.next return None ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值