File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Solution:
3
+ 0. i will use prev, cur pointers in for loop,
4
+ so i have to get rid of edge case when len of nums is at most 1
5
+ 1. use hash set for remove duplicate elements
6
+ 2. sort list
7
+ 3. iterate sorted_nums and use two pointers (prev, cur)
8
+ compare prev and cur and count if the difference is 1
9
+ 4. use max method, memorize maxCount
10
+ 5. return maxCount
11
+
12
+ Time Complexity:
13
+ 1. remove duplicate by hash set -> O(n)
14
+ 2. sort the list -> O(n log n)
15
+ 3. iterate sorted_nums -> O(n)
16
+
17
+ so time complexity of this solution will be O(n log n)
18
+
19
+ Space Complexity:
20
+ 1. set() -> O(n)
21
+ 2. sorted_nums -> O(n)
22
+ 3. count , maxCount -> O(1)
23
+
24
+ space complexity of this solution will be O(n)
25
+ """
26
+
27
+
28
+ class Solution :
29
+ def longestConsecutive (self , nums : List [int ]) -> int :
30
+ if len (nums ) <= 1 :
31
+ return len (nums )
32
+
33
+ sorted_nums = sorted (list (set (nums )))
34
+
35
+ count = 1
36
+ maxCount = 1
37
+ for i in range (1 , len (sorted_nums )):
38
+ prev = sorted_nums [i - 1 ]
39
+ cur = sorted_nums [i ]
40
+ if prev + 1 == cur :
41
+ count += 1
42
+ maxCount = max (count , maxCount )
43
+ else :
44
+ count = 1
45
+
46
+ return maxCount
You can’t perform that action at this time.
0 commit comments