File tree 2 files changed +32
-0
lines changed
2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change 54
54
118|[ Pascal's Triangle] ( ./0118-pascals-triangle.js ) |Easy|
55
55
119|[ Pascal's Triangle II] ( ./0119-pascals-triangle-ii.js ) |Easy|
56
56
121|[ Best Time to Buy and Sell Stock] ( ./0121-best-time-to-buy-and-sell-stock.js ) |Easy|
57
+ 128|[ Longest Consecutive Sequence] ( ./0128-longest-consecutive-sequence.js ) |Medium|
57
58
133|[ Clone Graph] ( ./0133-clone-graph.js ) |Medium|
58
59
136|[ Single Number] ( ./0136-single-number.js ) |Easy|
59
60
141|[ Linked List Cycle] ( ./0141-linked-list-cycle.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 128. Longest Consecutive Sequence
3
+ * https://leetcode.com/problems/longest-consecutive-sequence/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an unsorted array of integers nums, return the length of the
7
+ * longest consecutive elements sequence.
8
+ *
9
+ * You must write an algorithm that runs in O(n) time.
10
+ */
11
+
12
+ /**
13
+ * @param {number[] } nums
14
+ * @return {number }
15
+ */
16
+ var longestConsecutive = function ( nums ) {
17
+ const set = new Set ( nums ) ;
18
+ let result = 0 ;
19
+
20
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
21
+ if ( ! set . has ( nums [ i ] - 1 ) ) {
22
+ let streak = 1 ;
23
+ while ( set . has ( nums [ i ] + streak ) ) {
24
+ streak ++ ;
25
+ }
26
+ result = Math . max ( result , streak ) ;
27
+ }
28
+ }
29
+
30
+ return result ;
31
+ } ;
You can’t perform that action at this time.
0 commit comments