LeetCode Linked List Cycle II 逾時問題

來源:互聯網
上載者:User

標籤:style   blog   color   io   for   div   問題   log   sp   

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

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

 

題目意思很簡單,判斷鏈表是否有環,若有,返迴環的位置。

一開始,用了原來I的方法,結果會出現逾時。

    public ListNode detectCycle(ListNode head) {        boolean iscycle=false;          if (head!=null) {                ListNode temp=head;                while (!iscycle) {                    head=head.next;                    temp.next=temp;                    temp=head;                    if (head==null) {                                                return null;                    }else {                        if (head.next==head) {                            return head;                        }                    }                }        }        return head;    }

 

後來發現,我這個演算法必須遍曆完鏈表。

查看了網上其他方法。如下演算法:

    對於判斷鏈表是否有環,方法很簡單,用兩個指標,一開始都指向頭結點,一個是快指標,一次走兩步,一個是慢指標,一次只走一步,當兩個指標重合時表示存在環了。

    證明:假設鏈表有環,環的長度為N,慢指標在起始位置,快指標在位置k(位置從0開始計數),那麼快指標只要比慢指標多走經過N-k步,就可以追上慢指標了。。。,因為每一次快指標都比慢指標多走一步,所以一定可以在有限的步數追上慢指標。

  成功ac。

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {  public ListNode detectCycle(ListNode head) {    ListNode node = null;    if(head == null)      return node;    ListNode quick = head;    ListNode slow = head;        boolean tag = false;    while(quick!=null &&quick.next != null)    {      quick = quick.next;      quick = quick.next;      slow = slow.next;      if(quick == slow)      {        tag = true;        break;      }    }     if( tag  == false)    {      return node;    }    else    {      quick = head;      while( true)      {        if( quick == slow)        {          return quick;        }        else        {          quick = quick.next;          slow = slow.next;        }      }    }  }}

 

LeetCode Linked List Cycle II 逾時問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.