# [leetcode] 128. Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> hash(nums.begin(), nums.end());
int ret = 1;

for(auto num:nums) {
if(hash.find(num) == hash.end()) continue;
int cnt = 1;
int curNum = num;
hash.erase(num);
while(hash.find(curNum-1) != hash.end()) {
++cnt;
hash.erase(--curNum);
}
curNum = num;
while(hash.find(curNum+1) != hash.end()) {
++cnt;
hash.erase(++curNum);
}
ret = max(ret, cnt);
}

return ret;
}
};

• 本文已收录于以下专栏：

## [LeetCode]128.Longest Consecutive Sequence

Longest Consecutive Sequence Given an unsorted array of integers, find the length of the longes...
• SunnyYoona
• 2014年01月17日 22:16
• 1832

## [leetcode] 128. Longest Consecutive Sequence 解题报告

• qq508618087
• 2016年02月25日 02:13
• 1565

## LeetCode 128. Longest Consecutive Sequence

• zhyh1435589631
• 2016年03月24日 23:28
• 480

## 【LeetCode with Python】 Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. ...
• nerv3x3
• 2014年07月06日 15:09
• 2871

## [python]leetcode(128). Longest Consecutive Sequence

problem Given an unsorted array of integers, find the length of the longest consecutive element...
• 2017年09月10日 21:53
• 87

## Leetcode-549. Binary Tree Longest Consecutive Sequence II

• mcf171
• 2017年04月09日 11:23
• 772

## Longest Consecutive Sequence Leetcode Python

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. ...
• hyperbolechi
• 2015年01月19日 04:59
• 298

## LeetCode – Longest Consecutive Sequence Java

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. ...
• whywhom
• 2014年04月28日 08:29
• 423

## leetcode 298: Binary Tree Longest Consecutive Sequence

Binary Tree Longest Consecutive Sequence Total Accepted: 437 Total Submissions: 1351 Di...
• xudli
• 2015年10月29日 16:35
• 4781

## Longest Consecutive Sequence -- LeetCode

• linhuanmars
• 2014年04月05日 00:11
• 9303

举报原因： 您举报文章：[leetcode] 128. Longest Consecutive Sequence 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)