题解 | #链表中环的入口结点# 自定义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;
    }
}

有更好的哈希计算方法,我这里只是单纯为了好写,能跑通就是成功!

全部评论

相关推荐

小肥罗:此乃引蛇出洞之计,勾出你想去杭州的原因再告诉你不在杭州,让你打脸,自己离开。好一招抛砖引玉,虾仁猪心。你回复:计划去杭州,但我心中第一选择是宁波~巧了! 这计名叫“阿Q精神胜利法之厚脸皮不要脸我不尴尬谁爱尴尬谁尴尬去”之计!克制一切!
这个工作能去吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务