题解 | #链表中环的入口结点#

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        unordered_set<ListNode*> hashset;
        while( !hashset.count(pHead) && pHead!=nullptr){  //当pHead不在hash里面的时候
            hashset.insert(pHead);
            pHead = pHead->next;
        }
        //若无环,则pHead为null输出,若有环,则在该处跳出循环,依旧是pHead
        return pHead;


    }
};

用hash的方式处理,用空间换时间。因此空间复杂度为n,并不是1,虽然通过但并不满足要求。

全部评论

相关推荐

码砖:求职岗位要突出,一眼就能看到,教育背景放到最后,学校经历没那么重要,项目要重点突出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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