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: struct Node{ int lower; int higher; Node(int l, int h):lower(l),higher(h){ } }; int longestConsecutive(vector<int> &num) { map<int,Node> interval_map; map<int,Node>::iterator curr_iter,inc_iter,des_iter; int curr = 0; for(size_t i = 0; i < num.size(); i++){ curr = num[i]; curr_iter = interval_map.find(curr); if (curr_iter == interval_map.end()){ interval_map.insert(make_pair(curr,Node(curr,curr))); } } for(curr_iter = interval_map.begin(); curr_iter != interval_map.end(); curr_iter++) { int lower = curr_iter->second.lower; int higher = curr_iter->second.higher; int newlower = lower, newhigher = higher; des_iter = interval_map.find(lower - 1); if (des_iter != interval_map.end()) { curr_iter->second.lower = des_iter->second.lower; newlower = des_iter->second.lower; } inc_iter = interval_map.find(higher + 1); if (inc_iter != interval_map.end()){ curr_iter->second.higher = inc_iter->second.higher; newhigher = inc_iter->second.higher; } if (des_iter != interval_map.end()){ des_iter->second.higher = newhigher; } if (inc_iter != interval_map.end()){ inc_iter->second.lower = newlower; } } int max = -1; for(curr_iter = interval_map.begin(); curr_iter != interval_map.end(); curr_iter++){ if (curr_iter->second.higher - curr_iter->second.lower + 1> max){ max = curr_iter->second.higher - curr_iter->second.lower + 1; } } return max; } };