Problem Description:
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.
Basic ideas:
The key that takes advantage of the map is the knowledge of sorting, inserting an array into the map, and then counting the longest lenth.
Code:
int longestconsecutive (vector<int> &num) { //c++ map<int,int> nummap; for (int i = 0; i < num.size (); i++) Nummap.insert (Make_pair (Num[i],num[i])); int len = 1; int tmp = 1; Map<int,int>::iterator iter = Nummap.begin (); int prenum = iter->first; iter++; for (; Iter!=nummap.end (); iter++) { if (iter->first-prenum = = 1) tmp++; else { if (tmp > len) len = tmp; TMP = 1; } Prenum = iter->first; } Len = (len > tmp)? len:tmp; return len; }
[Leetcode]