You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
/** * @param {number[]} nums * @return {number} */varlongestConsecutive=function(nums){//First, we need a set that stores UNIQUE numbersletset=newSet(nums);//initialize the longest result to 0letlongest=0;for(letiofset){//if this is not the start of consecutive sequence, skip this iterationif(set.has(nums[i]-1))continue;letlength=1;letcurr=nums[i];//if we have a sequence, increase the lengthwhile(set.has(curr+1)){curr++;length++;}//if this is longest consecutive sequencelongest=Math.max(length,longest);}returnlongest;};
The text was updated successfully, but these errors were encountered:
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
The text was updated successfully, but these errors were encountered: