zoukankan      html  css  js  c++  java
  • 牛客题霸NC04题解

    判断链表中是否有环

    牛客题霸NC93

    难度:Easy

    题目描述

    判断给定的链表中是否有环,你能给出空间复杂度img的解法么?

    题目解答

    1. Set+遍历

    遍历链表,将遍历的每个节点放到一个Set里。如果遍历过程中发现Set中已经存在该节点,则代表链表存在环;如果遍历到末尾,则代表链表无环。

    import java.util.*;
    /**
     * 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) {
            
            Set<ListNode> set = new HashSet<>();
            while(head != null){
                if(set.contains(head)){
                    return true;
                }
                set.add(head);
                head = head.next;
            }
            
            return false;
        }
    }
    

    时间复杂度:O(n)

    空间复杂度:O(n)

    2. 快慢指针相遇

    设置快慢两个指针,如果两个指针最终相遇,代表链表存在环;若快指针到达链表末尾,则代表不存在环。

    /**
     * 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 || head.next == null){
                return false;
            }
            
            ListNode slow = head, fast = head.next;
            while(fast != null && fast.next != null){
                if(slow == fast){
                    return true;
                }
                slow = slow.next;
                fast = fast.next.next;
            }
            
            return false;
        }
    }
    

    时间复杂度:O(n)

    空间复杂度:O(1)

  • 相关阅读:
    C# 添加修改防火墙端口及程序
    Winform 多线程--解决界面卡死问题
    ScreenOper
    KVM的VPS主机在Centos6.x下修改系统时间
    Java IO和File类
    Java动态代理Proxy类源码分析
    Java IO之字节流
    Java IO之字符流
    两台计算机之间如何通讯
    Java引用类型原理
  • 原文地址:https://www.cnblogs.com/qwer112/p/13948421.html
Copyright © 2011-2022 走看看