Problem:
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Explanation:
给定一个链表,判断是否有环。
My Thinking:
正向遍历链表,每遍历一个局结点就重新遍历检查该结点的下一个结点是否是之前的结点。
My Solution:
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode cur=head;
ListNode check=head;
while(cur!=null){
while(check!=cur){
if(cur.next==check){
return true;
}else{
check=check.next;
}
}
cur=cur.next;
check=head;
}
return false;
}
}
发现运行失败。
Optimum Thinking:
- 使用HashSet存放出现过的结点,使用contains方法判断结点是否已经出现过,时间复杂度为O(n)。
- 使用两个指针slow和fast,fast移动的速度是slow的两倍,如果出现环,fast一定会与slow相遇,时间复杂度为O(n)
Optimum Solution:
(1)
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> nodeset=new HashSet<>();
while(head!=null){
if(nodeset.contains(head)){
return true;
}else{
nodeset.add(head);
}
head=head.next;
}
return false;
}
}
(2)
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast=head;
ListNode slow=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast){
return true;
}
}
return false;
}
}