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.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
分析
最容易想到的方法是,用一個哈希表unordered_map<int, bool> visited,記錄每個元素是否被訪問過,一旦出現某個元素被重複訪問,說明存在環。空間複雜度O(n),時間複雜度O(N)。
最好的方法是時間複雜度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) {
// 設置兩個指針,一個快一個慢
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}