采用哈希表存储每个元素,然后遍历整个数组,遍历的时候求当前元素所在连续序列的长度。
如[3, 1, 2, 8, 9],存到哈希表之后,我们遍历这个数组,首先遇到的是3,我们在哈希表中查找3之前的连续数,以及查找3之后的连续数,查完就从哈希表中删除(因为是连续的,所以删除不会影响最终结果),并且更新结果。
代码如下:
//
// Created by jt on 2020/9/23.
//
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
/**
*
* @param num int整型vector
* @return int整型
*/
int longestConsecutive(vector<int>& num) {
// write code here
unordered_set<int> uset(num.begin(), num.end());
int res = 0;
for (auto &a : num) {
int left = a - 1, right = a + 1, cnt = 1;
while(uset.count(left) != 0) { uset.erase(left--); cnt++; }
while(uset.count(right) != 0) { uset.erase(right++); cnt++; }
res = max(res, cnt);
}
return res;
}
};
京公网安备 11010502036488号