zoukankan      html  css  js  c++  java
  • Detect loop in a singly linked list

    去Twitter面试的被问到这个问题,当时只想到了用HashMap的办法,这种办法时间复杂度O(n),空间复杂度是O(n), 更好的办法是用 FastRunner / SlowRunner approach。用两个pointer遍历链表,fast的速度是slow的两倍,如果有loop,二者一定会collide。

    boolean detectLoop(LinkedListNode head){
        LinkedList slow = head;
        LinkedList fast = head;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
         if(slow == fast){ return true; } } return false; }

     What if we want to find the start of the loop? 

  • 相关阅读:
    重排列
    最多分成多少块
    后面第一个大于
    走格子
    硬币游戏
    还是01串
    戴德兰
    个人所得税
    最长高地
    执行Commit时Oracle做哪些工作
  • 原文地址:https://www.cnblogs.com/Antech/p/3843895.html
Copyright © 2011-2022 走看看