Skip to content

Commit 55a53cc

Browse files
committed
[WHYjun] WEEK 01 solutions - (4/5)
1 parent 8b97e42 commit 55a53cc

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import heapq
2+
3+
class Solution:
4+
def longestConsecutive(self, nums: List[int]) -> int:
5+
# remove duplicates by using set
6+
numsSet = set(nums)
7+
8+
if len(numsSet) == 0 or len(numsSet) == 1:
9+
return len(numsSet)
10+
11+
# Use priority queue to sort in O(n)
12+
sorted = []
13+
for num in numsSet:
14+
heapq.heappush(sorted, num)
15+
16+
prev = heapq.heappop(sorted)
17+
answer, count = 1, 1
18+
19+
for i in range(len(numsSet) - 1):
20+
popped = heapq.heappop(sorted)
21+
if prev + 1 == popped:
22+
count += 1
23+
else:
24+
count = 1
25+
26+
prev = popped
27+
answer = max(answer, count)
28+
29+
return answer
30+
31+
def longestConsecutiveUsingSetOnly(self, nums: List[int]) -> int:
32+
# remove duplicates by using set
33+
numsSet = set(nums)
34+
35+
answer = 0
36+
37+
for num in numsSet:
38+
# continue if it's not the longest consecutive
39+
if num - 1 in numsSet:
40+
continue
41+
else:
42+
count = 1
43+
while num + count in numsSet:
44+
count += 1
45+
answer = max(answer, count)
46+
47+
return answer

0 commit comments

Comments
 (0)