# [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

2014-01-17 22:16:21

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

2016-02-25 02:13:43

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

2017-09-10 21:53:52

#### LeetCode 128. Longest Consecutive Sequence

2016-03-24 23:28:31

#### leetcode刷题系列C++-Longest Consecutive Sequence

2016-02-17 14:12:16

#### leetcode128--longest consecutive sequence(java)

2017-01-18 22:40:51

#### leetcode 298: Binary Tree Longest Consecutive Sequence

2015-10-29 16:35:32

#### Longest Consecutive Sequence -- LeetCode

2014-04-05 00:11:16

#### [LeetCode 128] - 最长连续序列(Longest Consecutive Sequence)

2017-02-06 09:05:24

#### LeetCode - 128. Longest Consecutive Sequence - 思路详解- C++

2017-01-16 22:23:07