给定一个未排序的整数数组,找出最长连续序列的长度。
说明
要求你的算法复杂度为O(n)
样例
给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4
#ifndef C124_H
#define C124_H
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Solution{
public:
/**
* @param nums: A list of integers
* @return an integer
*/
int longestConsecutive(vector<int> &num) {
// write you code here
int len = num.size();
priority_queue<int> que;
for (auto c : num)
{
que.push(c);
}
int m=1,n=1;
num.clear();
for (int i = 0; i < len; ++i)
{
num.push_back(que.top());
que.pop();
}
for (int i = 0; i < len - 1; ++i)
{
if (num[i] == num[i + 1] + 1)
{
m++;
}
else if (num[i] == num[i + 1])
{
continue;
}
else
{
n = n>m ? n : m;
m = 1;
}
}
n = n > m ? n : m;
return n;
}
};
#endif