floyd's cycle detect演算法
阿新 • • 發佈:2019-02-12
他得程式是
def findArrayDuplicate(array): assert len(array) > 0 # The "tortoise and hare" step. We start at the end of the array and try # to find an intersection point in the cycle. slow = len(array) - 1 fast = len(array) - 1 # Keep advancing 'slow' by one step and 'fast' by two steps until they # meet inside the loop. while True: slow = array[slow] fast = array[array[fast]] # print 'step: ', 's :',slow, ' f: ', fast if slow == fast: # print 'slow: ',slow break # Start up another pointer from the end of the array and march it forward # until it hits the pointer inside the array. finder = len(array) - 1 while True: slow = array[slow] finder = array[finder] # If the two hit, the intersection index is the duplicate element. if slow == finder: return slow
思路就是根據f(i)=A(i)這個函式,將問題抽象成一個閉環求交點得問題。不過我有點疑問,第一個while還好理解,第二while在我看來好像有死迴圈得可能。另外,只要是有限個數得陣列,根據其抽象都會形成一個環,比如[0,1,3,2], ...f(3)=2, f(2)=3...., so, 這個程式對錯誤資料毫不容錯。
ps。上面是我想錯了,第二個while那麼做是有理論依據的, 如下:
關於找到找到環的入口點的問題,當fast若與slow相遇時,slow肯定沒有走遍歷完連結串列,而fast已經在環內迴圈了n圈(1<=n)。假設slow走了s步,則fast走了2s步(fast步數還等於s 加上在環上多轉的n圈),設環長為r,則:
2s = s + nr
則: s = nr
設整個連結串列長L,入口環與相遇點距離為x,起點到環入口點的距離為a。
a + x = nr a + x = (n-1) r + r = (n-1)r + L - a a = (n-1)r + (L - a - x)(L – a – x)為相遇點到環入口點的距離,由此可知,從連結串列頭到環入口點等於(n-1)迴圈內環+相遇點到環入口點,於是我們從連結串列頭、與相遇點分別設一個指標,每次各走一步,兩個指標必定相遇,且相遇第一點為環入口點。