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.
Discuss
这个题目,由于时间的限制,不能用暴力来做。可以用map+标记完成。
1.首先把所有的数字都放入到hash map当中,这样就能够迅速访问所有的数字。
2.接着开始扫描数组,每次获取数组的一个数字,如果数字没有被访问过,那么分别向左和向右延伸到头,并计算连续数字的长度。在延伸
过程中访问到的数字,都标记为已访问,下次再数组当中访问到该数字,就不需要延伸了。
3.复杂度,map是O(log(n)),所有访问一遍是n*log(n),然后再延续一遍是2*n*log(n).所以总的也是O(n*log(n))。至于用hashMap,使得hash的过程中,复杂度是O(1),那么就符合题目要求了。
/** * Because we must find the consecutive numbers, randomly find a number, and extend it by one, * to see whether it is consecutive on the larger end and little end. and add the number of * the larger extends and little extends. and then compare it to the max consecutive number. * */ class Solution { public: int longestConsecutive(vector<int> &num) { set<int> nums; set<int>::iterator ite; int res,res1,val; // add all the number in set; for(int i=0;i<num.size();i++) { nums.insert(num[i]); } res = 0; // scan the array, to find some consecutive sequence for(int i=0;i<num.size();i++) { ite = nums.find(num[i]); if(ite!=nums.end()) { res1 = 0; val = num[i]; //search towards the small numbers while((ite=nums.find(val))!=nums.end()) { res1++; nums.erase(val); val--; } val = num[i]+1; //search towards the large numbers while((ite=nums.find(val))!=nums.end()) { res1++; nums.erase(val); val++; } res = max(res,res1); } } return res; } };