题解 | #链表中环的入口结点# 自定义Hash
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
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 << 14);
}
if (node.next != null) {
hash = node.next.val << 7 ^ hash;
}
System.out.println(node.val);
System.out.println(hash);
return hash;
}
public ListNode EntryNodeOfLoop(ListNode pHead) {
HashMap<Integer, ListNode> hmap = new HashMap<>();
while (pHead != null) {
if (hmap.containsKey(computedHash(pHead))) {
return hmap.get(computedHash(pHead));
}
hmap.put(computedHash(pHead), pHead);
pHead = pHead.next;
}
return null;
}
}
有更好的哈希计算方法,我这里只是单纯为了好写,能跑通就是成功!
联想公司福利 1506人发布
