问题描述:
给定一个链表,判断链表中是否有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
题目地址:https://leetcode-cn.com/problems/linked-list-cycle/
解法一:HashSet判断是否成环
思路:
head, head.next,head.next.next。。。。存入HashSet集合中
判断是否重复,重复则成环
AC代码:
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> set = new HashSet<ListNode>();
while(head != null) {
if(!set.add(head)) {
return true;
}
head = head.next;
}return false;
}
}
分析:
时间复杂度O(N): 为链表的长度
空间复杂度O(N): 为维护HashSet所需的空间
解法二:快慢指针判断是否成环(优化)
思路:
通过一个快指针:fast = head.next.next
和一个慢指针:slow=head.next
慢指针去追快指针,如果追到那么快指针在循环那么链表成环。
AC代码:
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null)
return false;
ListNode fast = head.next;
ListNode slow = head;
while(slow != fast) {
if(fast == null || fast.next == null)
return false;
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
分析:
时间复杂度O(N): 为链表长度
空间复杂度O(1): 所需额外空间为常数阶