LeetCode128: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.
解题思路:
考虑到题目要求的时间复杂度O(n),很自然的想到哈希表,只有哈希表的查找时间为O(1)。
实现代码:
#include <iostream> #include <vector> #include <unordered_set> using namespace std; /* 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> &num) { if(num.empty()) return 0; unordered_set<int> iset; vector<int>::iterator iter; for(iter = num.begin(); iter != num.end(); ++iter) iset.insert(*iter); int max = 0; for(iter = num.begin(); iter != num.end(); ++iter) { if(iset.count(*iter) == 1) { int c = 1; int g = *iter + 1; while(iset.count(g) == 1) { iset.erase(g);//找到后记得要删除,不然会重复做,超时 c++; g++; } int l = *iter - 1; while(iset.count(l) == 1) { iset.erase(l); c++; l--; } if(max < c) max = c; } } return max; } }; int main(void) { int arr[] = {100, 4, 200, 1, 3, 2}; int n = sizeof(arr) / sizeof(arr[0]); vector<int> num(arr, arr+n); Solution solution; int max = solution.longestConsecutive(num); cout<<max<<endl; return 0; }
-----------------------我和我追猪的梦-----------------------------------------------------------------
作者:mickole