• 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
    }
    
  • 相关阅读:
    [日常训练]FJ省夏令营day1
    [vijos1002][NOIP2005]过河
    [poj2446]Chessboard
    [bzoj1854][SCOI2010]游戏
    [模板]匈牙利算法
    [bzoj3670][2014湖北省队互测week2]似乎在梦中见过的样子
    笔记3-27
    笔记3-26
    笔记3-25
    Codeforces891C. Envy
  • 原文地址:https://www.cnblogs.com/mapoos/p/14368984.html
Copyright © 2020-2023  润新知