Leetcode第128题 最长连续序列

用hash表去存储,初始val为0,然后设置一次遍历hash表,如果遍历过为1。当val没有遍历过,开始循环,设置左右指针,查询左右指针是否存在,存在的话,计数+1。直到不存在,比较count和result,保存最大值。

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int,int> hashmap;
        for(int i=0;i<nums.size();i++)
        if(!hashmap.count(nums[i]))
        hashmap[nums[i]]=0;
        int pmove,lmove,rmove,count,result=0;
        for(unordered_map<int,int>::iterator it=hashmap.begin();it!=hashmap.end();it++)
        {
            pmove=(*it).first;
            if(hashmap[pmove])
                continue;
            else
            {
                count=1;
                lmove=pmove-1;rmove=pmove+1;
                while(hashmap.count(lmove))
                    count++;hashmap[lmove--]=1;
                while(hashmap.count(rmove))
                    count++;hashmap[rmove++]=1;
            }
            result=result>count?result:count;
        }
        return result;
    }
};

也可以使用set,但是set插入的时候回自动排序,所以跟先排序一样了。先排序的话,就只有右侧增长,不存在左指针了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值