Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解释:题目言简意赅,判断是否有环。
有三种情况:无环、中途有环、首尾相接
思路一: 遍历全链,每个已遍历节点存入hash表中,发生冲突即为有环。
时间复杂度:O(n) 遍历全表
空间复杂风度:O(n) hash表存储全链
public boolean hasCycle(ListNode head) {
Set<ListNode> nodesSeen = new HashSet<>();
while (head != null) {
if (nodesSeen.contains(head)) {
return true;
} else {
nodesSeen.add(head);
}
head = head.next;
}
return false;
}
思路二:两个指针:fast每次移动两格,slow每次移动一格。若存在环,则在O(K)时间内fast可追上slow,K为环的长度。再加上未进入环时所耗时O(N),时间复杂度O(N+K),即O(N)
空间复杂度O(1)
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if((head==null)||head.next==null) return false;
ListNode fast = head.next;
ListNode slow = head;
while(fast!=slow){
if(fast.next==null||fast.next.next==null) return false;
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}