128.Longest Consecutive Sequence
My code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
self.data = {}
self.count = 0
for s in nums:
self.data[s] = 1
for s in self.data:
cur_count = 1
target = s + 1
while target in self.data:
cur_count += 1
target += 1
if cur_count >= self.count:
self.count = cur_count
cur_count = 1
return self.count
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
self.data = {}
self.count = 1
for s in nums:
self.data[s] = 1
for s in self.data:
if s - 1 not in self.data:
cur_count = 1
while s + 1 in self.data:
cur_count += 1
s += 1
if cur_count >= self.count:
self.count = cur_count
cur_count = 1
return self.count
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def longestConsecutive(self, nums: List[int]) -> int:
self.data = {}
self.count = 0
for s in nums:
self.data[s] = 1
for s in self.data:
if s - 1 not in self.data:
cur_count = 1
while s + 1 in self.data:
cur_count += 1
s += 1
self.count = max(cur_count,self.count)
return self.count
1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[13], line 1
----> 1 longestConsecutive([6, 7, 100, 5, 4, 4])
Cell In[12], line 2, in longestConsecutive(nums)
1 def longestConsecutive(nums) -> int:
----> 2 self.data = {}
3 self.count = 1
5 for s in nums:
NameError: name 'self' is not defined
1