题目:leetcode
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.
分析:
用一个哈希表,记录一个数是否已经被遍历,避免重复。
leetcode的测试用例没有考虑输入数组包含int类型最大最小值的问题。如输入[0x7fffffff,0x80000000],理应返回1,但如果没有考虑int类型最大最小值的问题,会返回2(即认为 0x7fffffff和0x80000000是两个相邻的数)。
int longestConsecutive(vector<int> &num) { if(num.size()<=1) return num.size(); unordered_map<int,bool> n; for(auto &i:num) { n[i]=false; } int res=1; for(int i=0;i<num.size();i++) { if(n[num[i]]==true) continue; int length=1; if(num[i]!=0x80000000) { int number=num[i]-1; while(n.find(number)!=n.end()) { n[number]=true; number--; length++; if(number==0x80000000) break; } } if(num[i]!=0x7fffffff) { int number=num[i]+1; while(n.find(number)!=n.end()) { n[number]=true; number++; length++; if(number==0x7fffffff) break; } } res=max(res,length); } return res; }
【哈希表】Longest Consecutive Sequence
原文地址:http://blog.csdn.net/bupt8846/article/details/44902777