1. 程式人生 > >LeetCode刷題EASY篇Linked List Cycle

LeetCode刷題EASY篇Linked List Cycle

題目

判斷一個連結串列是否有環

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

%e9%93%be%e8%a1%a8%e5%9b%be1

我的嘗試

沒有思路

正確解法

1.利用額外空間

利用set儲存訪問過的節點,如果已經訪問過,表示有環。時間複雜度O(n),空間O(n)

/**
 * 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;
            }
            else{
                set.add(head);
            }
            head=head.next;
        }
        return false;
    }
}

2. 兩個指標

空間複雜度降為O(1)

一個快指標,一個滿指標,如果有環,終將相遇。

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