最长的连续元素序列长度

最长的连续元素序列长度

http://www.nowcoder.com/questionTerminal/57d83a2501164168841c158a7535b458

采用哈希表存储每个元素,然后遍历整个数组,遍历的时候求当前元素所在连续序列的长度。

[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;
    }
};
刷遍天下无敌手 文章被收录于专栏

秋招刷题历程

全部评论

相关推荐

数开小菜鸡_暂退沉淀版:大二第三段,还是字节,这下真得点点举办了
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

更多
牛客网
牛客企业服务