去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?