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
    }
    
  • 相关阅读:
    修复 Visual Studio Error “No exports were found that match the constraint”
    RabbitMQ Config
    Entity Framework Extended Library
    Navisworks API 简单二次开发 (自定义工具条)
    NavisWorks Api 简单使用与Gantt
    SQL SERVER 竖表变成横表
    SQL SERVER 多数据导入
    Devexpress GridControl.Export
    mongo DB for C#
    Devexress XPO xpPageSelector 使用
  • 原文地址:https://www.cnblogs.com/mapoos/p/14368984.html
Copyright © 2011-2022 走看看