给定一个未排序的整数数组,找出最长连续序列的长度。
样例
样例 1
输入 : [100, 4, 200, 1, 3, 2]
输出 : 4
解释 : 这个最长的连续序列是 [1, 2, 3, 4]. 返回所求长度 4
说明
要求你的算法复杂度为O(n)
class Solution {
public:
/**
* @param num: A list of integers
* @return: An integer
*/
int longestConsecutive(vector<int> &num) {
// write your code here
if(num.size()==0) return 0;
sort(num.begin(),num.end());
int cnt=1;
int max=1;
int temp=num[0];
for (int i = 1; i < num.size(); i++) {
/* code */
if(num[i]==temp+1) {cnt++;temp+=1;}
else if(num[i]==temp) continue;
else
{
temp=num[i];
max=max>=cnt?max:cnt;
cnt=1;
}
}
max=max>cnt?max:cnt;
return max;
}
};