leetcode128. 最长连续序列 (hash表模拟查找)

链接:https://leetcode-cn.com/problems/longest-consecutive-sequence/

题目

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

用例

示例 1:

输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:

输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
 
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109

思路

很简单,因为无视顺序
可以将数据放入hash表
对每个数据进行前后序列数据查询
每查询到一个数,就对其删除;
对比最长序列计数;

代码

  class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int>us;
        for(auto &n :nums)
            us.insert(n);
        int ans= 0;
        while(!us.empty())
        {
            int cur=*us.begin();
            int l=cur,r=cur;
            us.erase(cur);
            while(us.find(l-1)!=us.end())
            {   --l;
                us.erase(l);
                
            }
            while(us.find(r+1)!=us.end())
            {
                ++r;
                us.erase(r);
            }
            ans=max(ans,r-l+1);
        }
        return ans;
    }
};
posted @ 2021-09-09 14:33  kitamu  阅读(39)  评论(0)    收藏  举报
Live2D