File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Title: 128. Longest Consecutive Sequence
3
+ Link: https://leetcode.com/problems/longest-consecutive-sequence/
4
+
5
+ Question:
6
+ - Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
7
+ - You must write an algorithm that runs in O(n) time.
8
+
9
+ Constraints:
10
+ - 0 <= nums.length <= 10^5
11
+ - -10^9 <= nums[i] <= 10^9
12
+
13
+ Time Complexity:
14
+ - O(n log n)
15
+ Space Complexity:
16
+ - O(n)
17
+
18
+ Notes:
19
+ - sorted(nums)๋ฅผ ์ฌ์ฉํ๋ฉด TC๊ฐ O(n log n)์ด ๋์ด ๋ฌธ์ ์ ์กฐ๊ฑด์ ์ถฉ์กฑํ์ง ๋ชปํ์ง๋ง, ์ด ๋ฐฉ๋ฒ์ด ์ ๊ฐ ์๊ฐํด์ ํ ์ ์๋ ์ต์ ์ด๋ผ ์ผ๋จ ์ด๋๋ก ์ ์ถํฉ๋๋ค! ๋ค๋ฅธ ๋ถ๋ค ๋ต์ ์ฐธ๊ณ ํ์ฌ ๋ค์ ํ์ด๋ณด๊ฒ ์ต๋๋ค :)
20
+ """
21
+
22
+ class Solution :
23
+ def longestConsecutive (self , nums : List [int ]) -> int :
24
+ nums = sorted (nums )
25
+ max_length = 0
26
+ current_length = 1
27
+
28
+ for i in range (1 , len (nums )):
29
+ if nums [i ] == nums [i - 1 ] + 1 :
30
+ current_length += 1
31
+ elif nums [i ] == nums [i - 1 ]:
32
+ continue
33
+ else :
34
+ max_length = max (max_length , current_length )
35
+ current_length = 1
36
+
37
+ max_length = max (max_length , current_length )
38
+ return max_length
You canโt perform that action at this time.
0 commit comments