标签:长度 ret tco tps rcu nod 需要 constant ast
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.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
链表判断环问题, 传统解法把链表节点全部保存下来, 然后遍历看下一个节点是否已经保存过了. 时间复杂度O(N). 空间复杂度O(N).
如果不想用空间, 则用两个指针,一个走两步,一个走一步,有环的时候他们一定相遇. 时间复杂度比较随机, 但小于O(N).
例如链表的环外长度为6, 环的长度为10. 则一共需要走10步他们就能相遇. 链表总长度16
分析: 假设走N步, 那么相遇的时候快指针一定比慢指针多走一圈
2N - N = 环长度. N=环长度.所以
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { if(NULL==head) return false; ListNode *fast=head, *low=head; while(fast->next&&fast->next->next) { low=low->next; fast=fast->next->next; if(fast==low)return true; } return false; } };
标签:长度 ret tco tps rcu nod 需要 constant ast
原文地址:https://www.cnblogs.com/lychnis/p/12034530.html