2.1.6 longest consecutive sequence

/*************最长连续序列********************/
给定无序数组,找出最长连续序列,时间复杂度0(n)
思路:用一个哈希表unordered_map<int ,bool> 记录每个元素是否判断过
          用vector来存储无序数组,任选一个数,左右扩张,判断他的左右连续数是否在数组中,记录累加连续长度,直到不连续为止。为避免重复对连续序列进行统计,同时用 unordered_map 的second (bool)来记录该数是否已经访问过。

          对于一个数,判断他的相邻的数是否在vector里,要比判断vector的数是否连续要快且简单,这是一种思路的转变。



         设断点调试的过程,可以清晰的看到查找最长连续序列的过程


#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;


int longestConsecutiveSequence(const vector<int> &num)
{
    /***************** unordered_map 中 int对应数组元素,bool 表示是否已进行过判断,****************/
    unordered_map<int,bool> used;
    for(auto iter=num.begin();iter!=num.end();++iter)
    {    auto &i=*iter;
        used[i]=false;
    }

    int longest =0;
    for (auto iter=num.begin();iter!=num.end();++iter)
    {
        auto &i=*iter;
        if(used[i]) continue;  // false表示没判断;ture表示已判断过,跳过进入下一次迭代判断
        
        int length=1;
        used[i]=true;

        //判断i的连续的后一个数是否在数组中
        for (int j=i+1;used.find(j)!=used.end();++j)
        {
            used[j]=true;  // i的后一个数i+1,已判断过,将其在hash 中的状态置为ture
        ++ length;
        }

    //判断i的连续的前一个数是否在数组中
    for (int j=i-1;used.find(j)!=used.end();--j)
    {
        used[j]=true;   //i的前一个数
        ++length;
    }
    longest=max(longest,length);  //取单前数i和之前的数连续长度中的较大者

    
}
    return longest;

}


int main()
{
    int A[]={200,4,100,1,3,2,300,5,400};
    vector <int> m(A,A+9);
    cout<< longestConsecutiveSequence(m)<<endl;
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值