Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
一开始没有考虑空间复杂度,借助hashmap找到第一个出现重复的listnode:
Map<ListNode,Integer> map=new HashMap<>(); while(head!=null) { if(map.get(head)==null) { map.put(head,1); head=head.next; } else return true; } return false;后来看到了只想到了时间复杂度为O(n^2)的方法,对每个节点查找是否有环,效率不高,在网上看到一个很好的方法,以下部分纯转载:
使用两个指针slow,fast。两个指针都从表头开始走,slow每次走一步,fast每次走两步,如果fast遇到null,则说明没有环,返回false;如果slow==fast,说明有环,并且此时fast超了slow一圈,返回true。
为什么有环的情况下二者一定会相遇呢?因为fast先进入环,在slow进入之后,如果把slow看作在前面,fast在后面每次循环都向slow靠近1,所以一定会相遇,而不会出现fast直接跳过slow的情况。
public boolean hasCycleII(ListNode head) { ListNode fast=head; ListNode slow=head; do { if(slow==null||fast==null) return false; slow=slow.next; fast=fast.next; if(fast==null) return false; fast=fast.next; }while(slow!=fast); return true; }