LeetCode141.环形链表

题目地址:https://leetcode-cn.com/problems/linked-list-cycle/

 

题目描述:给定一个链表,判断链表中是否有环。

解法一:哈希表。

 

遍历链表将每个节点存入哈希表中,哈希表中如果存在该节点,则说明有环。

时间复杂度:O(N),添加一个节点需要O(1).

空间复杂度:O(n),空间取决于添加到哈希表中的元素数目,最多可以添加 n 个元素。

public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        HashSet<ListNode> set = new HashSet<>();

        while(head != null){
            if(set.contains(head)){
                return true;
            }else{
                set.add(head);
            }
            head = head.next;
        }
        return false;
    }

解法二:快慢指针

 

快指针一次走2步,慢指针一次走1步,如果有环,那么两者必会相遇。如果无环,快指针将会走到null。

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

 

posted @ 2020-09-28 14:31  硬盘红了  阅读(134)  评论(0编辑  收藏  举报