# leetcode128.最长连续序列(Leetcode128. Longest continuous sequence)-其他

## leetcode128.最长连续序列(Leetcode128. Longest continuous sequence)

### 用例

``````输入：nums = [100,4,200,1,3,2]

``````
``````输入：nums = [0,3,7,2,5,8,4,6,0,1]

``````

### 求解

``````/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
let res = 0
//创建哈希表
let hash = new Object()
for(let i=0;i<nums.length;i++){
if(!hash[nums[i]]){
let left_length = hash[nums[i]-1] || 0
let right_length = hash[nums[i]+1] || 0
let new_length = left_length+right_length+1
hash[nums[i]]=new_length
res = Math.max(new_length,res)
hash[nums[i]-left_length]=new_length
hash[nums[i]+right_length]=new_length
}
}
return res
};
``````
————————

### subject

Given an unordered integer array nums, find the length of the longest sequence of consecutive numbers (sequence elements are not required to be continuous in the original array).

Please design and implement an algorithm with time complexity O (n) to solve this problem.

### Use case

``````输入：nums = [100,4,200,1,3,2]

``````
``````输入：nums = [0,3,7,2,5,8,4,6,0,1]

``````

### solve

``````/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
let res = 0
//创建哈希表
let hash = new Object()
for(let i=0;i<nums.length;i++){
if(!hash[nums[i]]){
let left_length = hash[nums[i]-1] || 0
let right_length = hash[nums[i]+1] || 0
let new_length = left_length+right_length+1
hash[nums[i]]=new_length
res = Math.max(new_length,res)
hash[nums[i]-left_length]=new_length
hash[nums[i]+right_length]=new_length
}
}
return res
};
``````