Leetcode 128 Longest Consecutive Sequence
Longest Consecutive Sequence – LeetCode
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.
The key for the solution is the sort the nums
array first before we loop through it. In each iteration, we need to check a couple of things:
- Is the current number the same with the last one? If yes we skip to the next iteration
- If the current number is not consecutive from the last number, we need update the value of the
temp
andresult
- At the end, we need to return the larger one between
temp
andresult
because the last iteration will not necessarily update theresult
value if it’s still consecutive.
Solution
/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
nums.sort((a, b) => a - b);
let result = 0;
let temp = 0;
for(let i = 0; i < nums.length; i++) {
if(nums[i] === nums[i - 1]) {
continue
}
if(temp === 0 || nums[i] - nums[i - 1] === 1) {
temp++
} else {
if(temp > result) {
result = temp;
}
temp = 1
}
}
return Math.max(temp, result)
};