Doing something you intrinsically are enthusiastic with.

2016年2月22日 星期一

Leetcode-LinkedList circle detection

凌晨3:24 Posted by Unknown No comments


問題:

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

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



這題算是很常見的題目

我記得群暉也有考過

並不難


結構上會給你一個Linklist

直覺解法是可以在結構裡面加一個遞增變數

然後一層一層標記,最後只要遇到下一個標記比現在的短就算Circle

不過這裡沒辦法給你改結構,而且這樣就要額外空間

採用另一個簡單的方法


就是slow,一次走一步

另一個fast,一次走兩步

然後只要有Circle,Fast遲早會在某地和slow相會




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

0 意見:

張貼留言