題目
https://leetcode.com/problems/longest-consecutive-sequence/
題解
方法1:HashMap 解法,O(n^2)
如下圖,假設(shè) n=4 被插入,count 的變化如下:
class Solution { public int longestConsecutive ( int [ ] nums
) { HashMap < Integer , Integer > dp
= new HashMap < > ( ) ; for ( int n
: nums
) { if ( ! dp
. containsKey ( n
) ) { int count
= 1 ; if ( dp
. containsKey ( n
- 1 ) ) { count
+= dp
. get ( n
- 1 ) ; } dp
. put ( n
, count
) ; int next
= n
+ 1 ; while ( dp
. containsKey ( next
) ) { dp
. put ( next
, dp
. get ( next
) + count
) ; next
++ ; } } } int max
= 0 ; for ( int k
: dp
. keySet ( ) ) { max
= Math . max ( max
, dp
. get ( k
) ) ; } return max
; }
}
方法2:官方題解,O(n)
https://leetcode.com/problems/longest-consecutive-sequence/solution/
class Solution { public int longestConsecutive ( int [ ] nums
) { Set < Integer > num_set
= new HashSet < Integer > ( ) ; for ( int num
: nums
) { num_set
. add ( num
) ; } int longestStreak
= 0 ; for ( int num
: num_set
) { if ( ! num_set
. contains ( num
- 1 ) ) { int currentNum
= num
; int currentStreak
= 1 ; while ( num_set
. contains ( currentNum
+ 1 ) ) { currentNum
+= 1 ; currentStreak
+= 1 ; } longestStreak
= Math . max ( longestStreak
, currentStreak
) ; } } return longestStreak
; }
}
方法3:dp
如果 num 的加入使連續(xù)序列的長(zhǎng)度增加,那么一定是因?yàn)樗c num-1 或 num+1 連成了一片。 連成一片后,只需要讓連續(xù)序列的兩個(gè)端點(diǎn)保持最新記錄,不需要關(guān)心除端點(diǎn)以外的元素。
class Solution : def
longestConsecutive ( self
, nums
: List [ int ] ) -> int : result
= 0 record = { } for num in nums
: if num in
record : continue l
, r
= num
, num
if num
- 1 in
record : l
= record [ num
- 1 ] [ 0 ] if num
+ 1 in
record : r
= record [ num
+ 1 ] [ 1 ] if r
- l
+ 1 > result
: result
= r
- l
+ 1 record [ num
] = ( l
, r
) # 占位,避免重復(fù)
record [ l
] = ( l
, r
) record [ r
] = ( l
, r
) for r in
record : print ( str ( r
) + ": " + str ( record [ r
] ) ) return result
總結(jié)
以上是生活随笔 為你收集整理的leetcode 128. Longest Consecutive Sequence | 128. 最长连续序列(Java) 的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。