File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 128. Longest Consecutive Sequence
3
+ * Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
4
+ *
5
+ * You must write an algorithm that runs in O(n) time.
6
+ * https://leetcode.com/problems/longest-consecutive-sequence/description/
7
+ */
8
+ function longestConsecutive ( nums : number [ ] ) : number {
9
+ const set = new Set ( nums ) ;
10
+ const sorted = [ ...set ] . sort ( ( a , b ) => a - b ) ;
11
+
12
+ if ( sorted . length === 0 ) {
13
+ return 0 ;
14
+ }
15
+
16
+ let longestSequence = 1 ;
17
+ let currentSequence = 1 ;
18
+ for ( let i = 0 ; i - 1 < sorted . length ; i ++ ) {
19
+ if ( Math . abs ( sorted [ i + 1 ] - sorted [ i ] ) === 1 ) {
20
+ currentSequence ++ ;
21
+ } else {
22
+ if ( currentSequence > longestSequence ) {
23
+ longestSequence = currentSequence ;
24
+ }
25
+ currentSequence = 1 ;
26
+ }
27
+ }
28
+
29
+ return longestSequence ;
30
+ }
31
+
32
+ // O(n) time
33
+ // O(n) space
You can’t perform that action at this time.
0 commit comments