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.
unordered_set是C++自带的hash表
class Solution { public: int longestConsecutive(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function if(num.size()==0)return 0; unordered_set<int> m; for(int i=0;i<num.size();i++){ m.insert(num[i]); } int max=0; while(m.size()!=0){ int v=*m.begin(); m.erase(v); int i1=0,i2=0,v1=v-1,v2=v+1; while(m.find(v1)!=m.end()){ m.erase(v1); v1--; i1++; } while(m.find(v2)!=m.end()){ m.erase(v2); v2++; i2++; } int length=i1+i2+1; if(length>max){ max=length; } } return max; } };