141.Linked List Cycle---双指针

时间:2023-03-10 06:58:02
141.Linked List Cycle---双指针

题目链接

题目大意:给出一个链表,判断该链表是否有环,空间复杂度最好控制在o(1)

这个题没有给测试用例,导致没太明白题目意思,看了题解,用了两种方法示例如下:

法一(借鉴):利用两个指针,一个指针步长为2,一个指针步长为1,若链表中有环,则两个指针同时走,在某一时刻一定会走到一起;若链表中没有环,则两个指针一定会走到null,代码如下(耗时1ms):

     public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && slow != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
return true;
}
}
return false;

法二(借鉴):利用set集合中的contains,判断是否有两个相同的结点在集合中,如果有,则有环,代码如下(耗时10ms):

         Set<ListNode> list = new HashSet<>();
while(head != null) {
if(list.contains(head)) {
return true;
}
else {
list.add(head);
head = head.next;
}
}
return false;