File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Linear Search With A Hash Map
3
+ // Time: O(n)
4
+ // Space: O(n)
5
+ // This solution only makes one pass over the `nums` array and is the highest
6
+ // performing solution.
7
+ //////////////////////////////////////////////////////////////////////////////
8
+
9
+ /**
10
+ * @param {number[] } nums
11
+ * @return {number }
12
+ */
13
+ function longestConsecutive ( nums ) {
14
+
15
+ if ( ! nums . length ) {
16
+ return 0 ;
17
+ }
18
+
19
+ const map = Object . create ( null ) ;
20
+ let max = 0 ;
21
+
22
+ for ( const num of nums ) {
23
+
24
+ if ( num in map ) {
25
+ continue ;
26
+ }
27
+
28
+ const prev = num - 1 ;
29
+ const next = num + 1 ;
30
+ let len = 1 ;
31
+
32
+ if ( prev in map ) {
33
+ if ( next in map ) {
34
+ len += map [ prev ] + map [ next ] ;
35
+ map [ prev - map [ prev ] + 1 ] = len ;
36
+ map [ next + map [ next ] - 1 ] = len ;
37
+ } else {
38
+ len += map [ prev ] ;
39
+ ++ map [ prev - map [ prev ] + 1 ] ;
40
+ }
41
+ } else if ( next in map ) {
42
+ len += map [ next ] ;
43
+ ++ map [ next + map [ next ] - 1 ] ;
44
+ }
45
+ map [ num ] = len ;
46
+ max = Math . max ( max , len ) ;
47
+ }
48
+
49
+ return max ;
50
+ }
51
+
1
52
//////////////////////////////////////////////////////////////////////////////
2
53
// Linear Search With A Hash Set
3
54
// Time: O(n)
You can’t perform that action at this time.
0 commit comments