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.
思路:
因为用排序的话就需要nlgn,而题目要求是O(n),所以考虑到用哈希。先将原表中的数都存入hash表中,然后遍历原数组,如果存在某个数的话,就看它之前和之后的数有多少存在,没访问到一个就从hash表中删除,避免重复。在用一个result保存中间结果即可。
代码:
1 if(len == 0) 2 return 0; 3 for(i = 0; i < len; i++) 4 table[num[i]] = i; 5 for(i = 0; i < len; i++){ 6 int tmp = num[i]; 7 if(table.find(tmp) != table.end()){ 8 t = 0; 9 while(table.find(tmp) != table.end()){ 10 table.erase(tmp); 11 tmp--; 12 t++; 13 } 14 tmp = num[i]+1; 15 while(table.find(tmp) != table.end()){ 16 table.erase(tmp); 17 tmp++; 18 t++; 19 } 20 if(t > result) 21 result = t; 22 } 23 } 24 return result; 25 }