Skip to content

Commit dd8332d

Browse files
committed
最长连续序列
1 parent c0ae760 commit dd8332d

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

longest_consecutive_sequence.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param num, a list of integer
6+
@return an integer
7+
"""
8+
def longestConsecutive(self, num):
9+
# write your code here
10+
ret = 0
11+
if num:
12+
neighbors = {} # 记录每个数的相邻数字,+-1。
13+
for i in num:
14+
if i not in neighbors:
15+
neighbors[i] = 1
16+
for i in num:
17+
if neighbors[i]: # 一个数不会出现在2个序列中
18+
count = 1
19+
# 向上找
20+
target = i + 1
21+
while target in neighbors:
22+
neighbors[target] = None # 标记该数字已被使用
23+
target += 1
24+
count += 1
25+
# 向下找
26+
target = i - 1
27+
while target in neighbors:
28+
neighbors[target] = None
29+
target -= 1
30+
count += 1
31+
neighbors[i] = None
32+
ret = max(count, ret)
33+
return ret

0 commit comments

Comments
 (0)