这道题是一个比较简单的题目,由于题目中要求O(n),限制使用排序,所有借用hash表unordered_set<int> s来存储数组中元素,保证O(n)的时间复杂度。
题目:
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.
1 class Solution { 2 public: 3 int longestConsecutive(vector<int> &num) { 4 unordered_set<int> s(num.begin(),num.end()); 5 6 int res = 0; 7 for(int n : num){ 8 if(s.find(n) != s.end()){ 9 s.erase(n); 10 int pre = n - 1; 11 int post = n + 1; 12 while(s.find(pre) != s.end()){ 13 s.erase(pre--); 14 } 15 while(s.find(post) != s.end()){ 16 s.erase(post++); 17 } 18 res = max(res,post-pre-1); 19 } 20 } 21 return res; 22 } 23 };