LeetCode【longest-consecutive-sequence】

思路:
使用hash表来解决这个问题,先初试化一个hash表,存储所有数组元素,然后遍历这个数组,对找到的数组元素,去搜索其相连的上下两个元素是否在hash表中,如果在,删除相应元素并增加此次查找的数据长度,如果不在,从下一个元素出发查找,已经访问过的元素记录下来或者删除

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        unordered_set<int> myset(num.begin(), num.end());
        int res = 1;
        for (int i = 0; i < num.size(); i++)
        {
            int current = num[i];
            if (myset.find(current) == myset.end())
                continue;
            myset.erase(current);
            int prev = current-1, post = current+1;
            while (myset.find(prev)!=myset.end())
                myset.erase(prev--);
            while (myset.find(post) != myset.end())
                myset.erase(post++);
            res = max(res, post-prev-1);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/zishengzheng/article/details/81673873