zoukankan      html  css  js  c++  java
  • [leetcode-141-Linked List Cycle]

    Given a linked list, determine if it has a cycle in it.
    Follow up: Can you solve it without using extra space?

    判断链表是否带环,我们可以采用在头结点设两个指针,一个叫fast,一个叫slow,fast一下走两步,而slow一下走一步。
    如果链表中存在环的话,那么fast和slow必定会在环中相遇。若链表中没有环的话,

    那么fast必定现于slow指针先到达链表的尾节点(->next = Null)。
    为什么链表中存在环,则slow和fast会在环中相遇?
    可以联想在体育场里面跑步时候的场景,速度快和速度慢的在同一起点的话,必定在某个时间点,速度快的会追上速度慢的 。

    bool hasCycle(ListNode *head)
        {       while (fast != NULL && fast->next != NULL)
            {
                slow = slow->next;
                fast = fast->next->next;
                if (slow == fast) return true;
            }
            if (fast==NULL || fast->next ==NULL)//没有环
            {
                return false;
            }
            return true;
        }

     还有一个特别朴素的想法就是,使用hash表格来记录结点访问次数,时间复杂度为O(n),空间复杂度也为O(n)。

    但是经过测试,效率没有上边的方法高。

    bool hasCycle(ListNode *pHead) {
            if (pHead == NULL)return false;
            map<ListNode*, int> table;//用来记录访问次数
            ListNode* entry= NULL;
            while (pHead!=NULL)
            {
                table[pHead]++;
                if (table[pHead]==2)
                {
                    return true;
                }
                pHead = pHead->next;
            }
            return false;
        }
  • 相关阅读:
    Android studio USB连接失败
    BZOJ 1013 [JSOI2008]球形空间产生器sphere
    UVA1025
    noip2016天天爱跑步
    noip2015运输计划
    noip2012借教室
    BZOJ 1597: [Usaco2008 Mar]土地购买
    BZOJ1010: [HNOI2008]玩具装箱toy
    BZOJ1026: [SCOI2009]windy数
    BZOJ1801:[Ahoi2009]chess 中国象棋
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6442689.html
Copyright © 2011-2022 走看看