题解 | #两个链表的第一个公共结点# Hash 映射
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
// 计算哈希值
public int computedHash(ListNode node) {
int hash = 0;
if (node != null) {
hash += (node.val << 17);
}
if (node.next != null) {
hash = node.next.val << 3 ^ hash;
}
System.out.println(node.val);
System.out.println(hash);
return hash;
}
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
HashMap<Integer, ListNode> hmap = new HashMap<>();
while (pHead1 != null) {
hmap.put(computedHash(pHead1), pHead1);
pHead1 = pHead1.next;
}
while(pHead2 != null){
if(hmap.containsKey(computedHash(pHead2))){
return pHead2;
}
pHead2 = pHead2.next;
}
return null;
}
}
哈希函数不唯一,有时候不好用,就把哈希函数调的复杂一些,先计算第一个链表全部的hash值放入map,再遍历第二个链表,根据计算的哈希值就可以查询到对应的节点是否存在,并且返回该节点。
yysy,我的思路更接近于暴力,但是耐不住简单啊,hhh
