File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments