LeetCode Solution-141

Posted littledy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Solution-141相关的知识,希望对你有一定的参考价值。

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.

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.

思路
解释一下所给输入中包含pos的意思,因为给的函数里面并没有这个输入。pos存在的意义是为了构造一个有环或无环的链表(从尾节点指向pos指向的节点,为-1则无环),而我们所给的就是头结点head,所以不能用pos来判断是否有环。
1.设置2个指针:fast和slow;
2.fast每次移动2个节点,slow每次移动一个节点;
3.如果fast和slow指向的节点相同,说明有循环,不相同则说明不存在循环。

Solution:

bool hasCycle(ListNode *head) {
    if (!head) return false;
    
    ListNode *fast = head, *slow = head;
    while (fast->next && fast->next->next) {        //这种方法只能证明环存在,而不能找到环开始的节点位置
        fast = fast->next->next;
        slow = slow->next;
        if (fast == slow)   return true;
    }
    return false;
}

性能
Runtime: 12 ms  Memory Usage: 9.9 MB

以上是关于LeetCode Solution-141的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode.1024 视频拼接

LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段

LEETCODE 003 找出一个字符串中最长的无重复片段

Leetcode 763 划分字母区间

LeetCode:划分字母区间763

Leetcode:Task Scheduler分析和实现