zoukankan      html  css  js  c++  java
  • 0141. Linked List Cycle (E)

    Linked List Cycle (E)

    题目

    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(1))空间的方法是使用快慢指针,慢指针每次走一步,快指针每次走两步,如果快指针追上慢指针则说明存在环。实际上可以看做一个相遇问题,如果快慢指针都在一个环中,且快指针距离慢指针还有n个结点的距离,那么经过n个回合后快指针必定与慢指针重合。


    代码实现

    Java

    Hash

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null) {
                return false;
            }
    
            Set<ListNode> set = new HashSet<>();
            while (head != null) {
                if (!set.add(head)) {
                    return true;
                }
                head = head.next;
            }
            
            return false;
        }
    }
    

    快慢指针

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

    JavaScript

    /**
     * @param {ListNode} head
     * @return {boolean}
     */
    var hasCycle = function (head) {
      const nodes = new Set()
      while (head) {
        if (nodes.has(head)) {
          return true
        }
        nodes.add(head)
        head = head.next
      }
      return false
    }
    
  • 相关阅读:
    Javascript Promise技术
    什么是CPS
    移动端input file 提示没有应用可执行此操作
    黄聪:wordpress+Windows下安装Memcached服务及安装PHP的Memcached扩展
    黄聪:Windows下安装Memcached服务及安装PHP的Memcached扩展
    用VScode配置Python开发环境
    在VSCode中使用码云(Gitee)进行代码管理
    网页链接分享到微信朋友圈带图标和摘要的完美解决方法
    解决百度统计被刷广告的办法,屏蔽非法广告
    Visual Studio代码PHP Intelephense继续显示不必要的错误
  • 原文地址:https://www.cnblogs.com/mapoos/p/14368984.html
Copyright © 2011-2022 走看看