We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent c0ae760 commit dd8332dCopy full SHA for dd8332d
longest_consecutive_sequence.py
@@ -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
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
28
+ neighbors[target] = None
29
+ target -= 1
30
31
+ neighbors[i] = None
32
+ ret = max(count, ret)
33
+ return ret
0 commit comments