• 牛客题霸NC4(判断链表是否有环)


    判断给定的链表中是否有环
    扩展:
    你能给出空间复杂度的解法么?
    牛客题霸NC4

     使用快,慢指针可以无需额外空间,慢指针一次走一步,快指针一次走两步,若有环,两者必相遇,因为两者会在一个圈里面循环跑,一快一慢,快指针肯定会套圈(可以想象100000000000000000000000000000米田径赛跑,实力相差悬殊的情况下会出现套圈的现象)

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null){
                return false;
            }
            ListNode slow = head,fast = head;
            while(fast != null && fast.next != null){
                slow = slow.next;
                fast = fast.next.next;
                if(slow == fast){
                    return true;
                }
            }
            return false;
        }
    }
    View Code

     还有一个方法是使用LinkedList保存已出现的节点,每遍历一个节点就判断一下是否在LinkedList中出现过,代码略

    2020/10/09leetcode的每日一题,题解写法

     1 public class Solution {
     2     public boolean hasCycle(ListNode head) {
     3         if (head == null || head.next == null) {
     4             return false;
     5         }
     6         ListNode slow = head;
     7         ListNode fast = head.next;
     8         while (slow != fast) {
     9             if (fast == null || fast.next == null) {
    10                 return false;
    11             }
    12             slow = slow.next;
    13             fast = fast.next.next;
    14         }
    15         return true;
    16     }
    17 }
    View Code
  • 相关阅读:
    联赛膜你测试20 T1 Simple 题解 && NOIP2017 小凯的疑惑 题解(赛瓦维斯特定理)
    P5518
    快速除法 / 取模
    P6860
    spoj LCMSUM
    虚树 学习笔记
    长链剖分 学习笔记
    CF526G
    P4292
    01 分数规划(water)
  • 原文地址:https://www.cnblogs.com/yu-xia-zheng-ye/p/13560615.html
Copyright © 2020-2023  润新知