【LeetCode】Linked List Cycle 解题报告

Linked List Cycle

[LeetCode]

https://leetcode.com/problems/linked-list-cycle/

Total Accepted: 102417 Total Submissions: 277130 Difficulty: Easy

Question

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

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

Ways

审题!
第一想法是只要判断能否循环走到head就好了,代码也写出来了。不认为自己有错,但是总是超时。审题之后才知道,是否有环并不是说这个环中一定包括head,可以是一个小环。

错误代码:

/**
 * 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 move=head;
        while(move.next!=null && move.next!=head){
            move=move.next;
        }
        return move.next==head;
    }
}

时间溢出。

方法一

双指针的方法。

这个链表双指针第一次见。思路是两个指针,一个走的快一个走的慢,循环下去,只要两者能够重逢说明有环。

好厉害的思路!

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

AC:1ms

看了官方解答之后,发现可以优化,优化如下:

public class Solution {
    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.next==null || fast.next.next==null) return false;
            fast=fast.next.next;
            slow=slow.next;
        }
        return true;
    }
}

我想的是只要走的慢的这个不为空的话,就一直走好了。 官方解答想的是两者不重合就一直走。

方法二

官方解答的HashTable的方法。记录下来哪些已经走了,只要走到之前走过的节点说明有环。

public class Solution {
    public boolean hasCycle(ListNode head) {
        HashSet<ListNode> hash=new HashSet();
        while(head!=null){
            if(hash.contains(head)){
                return true;
            }else{
                hash.add(head);
            }
            head=head.next;
        }
        return false;
    }
}

AC:10ms

我以为这个空间复杂度小点时间会短一点。事实说明,HashSet每次查询速度还是太慢了哈。

Date

2016/5/2 17:24:37

你可能感兴趣的:(LeetCode)