File tree 1 file changed +11
-8
lines changed
1 file changed +11
-8
lines changed Original file line number Diff line number Diff line change 3
3
* https://leetcode.com/problems/longest-consecutive-sequence/
4
4
* Difficulty: Medium
5
5
*
6
- * Given an unsorted array of integers nums, return the length of the
7
- * longest consecutive elements sequence.
6
+ * Given an unsorted array of integers nums, return the length of the longest consecutive
7
+ * elements sequence.
8
8
*
9
9
* You must write an algorithm that runs in O(n) time.
10
10
*/
@@ -17,13 +17,16 @@ var longestConsecutive = function(nums) {
17
17
const set = new Set ( nums ) ;
18
18
let result = 0 ;
19
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 ++ ;
20
+ for ( const num of set ) {
21
+ if ( ! set . has ( num - 1 ) ) {
22
+ let count = 1 ;
23
+ let n = num ;
24
+
25
+ while ( set . has ( n + 1 ) ) {
26
+ n ++ ;
27
+ count ++ ;
25
28
}
26
- result = Math . max ( result , streak ) ;
29
+ result = Math . max ( result , count ) ;
27
30
}
28
31
}
29
32
You can’t perform that action at this time.
0 commit comments