-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path128. Longest Consecutive Sequence.py
84 lines (62 loc) · 1.94 KB
/
128. Longest Consecutive Sequence.py
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import heapq
from typing import List
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
heapq.heapify(nums)
result = 1
cur = heapq.heappop(nums)
curFreq = 1
while len(nums) > 0:
if nums[0] == cur:
cur = heapq.heappop(nums)
elif nums[0] == cur+1:
cur = heapq.heappop(nums)
curFreq += 1
else:
curFreq = 1
cur = heapq.heappop(nums)
result = max(result,curFreq)
return result
def longestConsecutive2023Solution(self, nums: List[int]) -> int:
if len(nums) == 0: return 0
result = 0
hs = set()
heapq.heapify(nums)
for num in nums: hs.add(num)
def findSmallest() -> int:
cur = heapq.heappop(nums)
# Because we don't want used values
while cur not in hs:
cur = heapq.heappop(nums)
return cur
sm = findSmallest()
cur = 0
while hs:
if sm in hs:
cur += 1
result = max(cur,result)
hs.remove(sm)
sm += 1
else:
sm = findSmallest()
cur = 0
continue
return result
# Solution using Heap
def longestConsecutiveHeap2022(self, nums: List[int]) -> int:
hashset = set()
result = 0
for num in nums:
hashset.add(num)
def getSeq(num,cur):
if num in hashset:
cur += 1
return getSeq(num+1,cur)
else:
return cur
for num in nums:
if num-1 not in hashset:
result = max(result,getSeq(num,0))
return result