class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums is None or len(nums) == 0:
return 0
num_set = set()
for num in nums:
num_set.add(num)
res = 1
for num in nums:
if num not in num_set:
continue
else:
num_set.remove(num)
forward_count = self.check_forwrad(num, num_set)
backward_count = self.check_backwrad(num, num_set)
res = max(res, 1 + forward_count + backward_count)
return res
def check_forwrad(self, num, num_set):
count = 0
num += 1
while num in num_set:
num_set.remove(num)
count += 1
num += 1
return count
def check_backwrad(self, num, num_set):
count = 0
num -= 1
while num in num_set:
num_set.remove(num)
count += 1
num -= 1
return count
Leetcode128.最长连续序列
猜你喜欢
转载自blog.csdn.net/weixin_36149892/article/details/101909722
今日推荐
周排行