forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_consecutive_sequence.py
More file actions
33 lines (32 loc) · 1.09 KB
/
Copy pathlongest_consecutive_sequence.py
File metadata and controls
33 lines (32 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding: utf-8 -*-
class Solution:
"""
@param num, a list of integer
@return an integer
"""
def longestConsecutive(self, num):
# write your code here
ret = 0
if num:
neighbors = {} # 记录每个数的相邻数字,+-1。
for i in num:
if i not in neighbors:
neighbors[i] = 1
for i in num:
if neighbors[i]: # 一个数不会出现在2个序列中
count = 1
# 向上找
target = i + 1
while target in neighbors:
neighbors[target] = None # 标记该数字已被使用
target += 1
count += 1
# 向下找
target = i - 1
while target in neighbors:
neighbors[target] = None
target -= 1
count += 1
neighbors[i] = None
ret = max(count, ret)
return ret