File tree Expand file tree Collapse file tree 1 file changed +11
-8
lines changed Expand file tree Collapse file tree 1 file changed +11
-8
lines changed Original file line number Diff line number Diff line change 33 * https://leetcode.com/problems/longest-consecutive-sequence/
44 * Difficulty: Medium
55 *
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.
88 *
99 * You must write an algorithm that runs in O(n) time.
1010 */
@@ -17,13 +17,16 @@ var longestConsecutive = function(nums) {
1717 const set = new Set ( nums ) ;
1818 let result = 0 ;
1919
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 ++ ;
2528 }
26- result = Math . max ( result , streak ) ;
29+ result = Math . max ( result , count ) ;
2730 }
2831 }
2932
You can’t perform that action at this time.
0 commit comments