2013年4月29日 星期一

整數集合找出最長連續數列長度


例子:

(1) { 1, 2, 3, 4 } returns 4

(2) { 4, 5, 6, 10, 11 } returns 3

(3) { 1, 2, 4, 5, 7, 8 } returns 2



我的想法來自於 DFS 的經典題目:grafixMask



這是演算法教學系列文章:

http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=alg_index

裡面有一篇不錯,雖然大學有教 graph algorithms,可惜當時沒有熱情,

我說的就是這篇:

Introduction to Graphs and Their Data Structures

((現在有熱情的理由也是很瞎,Candy Crush Saga 激起我解決問題的衝動,

數學問題太難,演算法問題可難可易,很適合我解決問題))



總之以 C# 的語言來說,

先把 int[] input 丟到 HashSet<int> numberSet = new HashSet<int>(input),

O(n)。

接著 iterate hash set,把每個整數點 p 當做一個 Node,

Edge 就是 p-1 或是 p+1,這個查詢只要 O(1),因此我們可以建出一個 graph,

space O(n)

((上班說錯更正一下,直接用 linked list 實做 graph 就可以了))



接著 grafixMask 技巧用下去,直接結束。

time complexity O(n)

space complexity O(n)



不過這比起 Candy Crush Saga Level 361,簡直小巫見大巫,

這關有夠機車的。

沒有留言:

張貼留言