题目
思路
用dict存储数组中所有元素。遍历数组中元素,判断左右元素是否在dict中,记录最大长度。
代码
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num_dict = {}
for num in nums:
num_dict[num] = 1
max_len = 0
for num in nums:
if num in num_dict:
count = 0
num_left = num - 1; num_right = num + 1
while num_right in num_dict:
count += 1
del num_dict[num_right]
num_right += 1
while num_left in num_dict:
count += 1
del num_dict[num_left]
num_left -= 1
del num_dict[num]
max_len = max(max_len, count + 1)
return max_len