leetcode Longest Consecutive Sequence

题意:给定一个整数数组,找出数组中最长的连续整数。时间要求是O(n)。

思路:一看时间复杂度要求就想到了hash,第一次先进行初始化操作,时间复杂度为O(n),然后遍历查找,时间复杂度以为O(n),在c++中利用了STL模板unordered_sort,类似于hash。喜欢的同学可以自己查找一下。

代码实现:

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = num.size();
        if(0 == len)
        {
            return 0;
        }
        
        unordered_set<int> temp;
        
        for(int i = 0; i < len; ++i)
        {
            temp.insert(num[i]);
        }
        
        int ans = 0;
        for(int i = 0; i < len; ++i)
        {
            int cur = num[i];
            int cnt = 0;
            if(temp.find(cur) != temp.end())
            {
                temp.erase(cur);
                cnt ++;
                cnt += getCount(temp, cur + 1, true);
                cnt += getCount(temp, cur - 1, false);
                
                ans = max(ans, cnt);
            }
        
        }
        
        return ans;
    }
    
    int getCount(unordered_set<int> &temp, int num, bool dir)
    {
        int cnt = 0;
        
        while(temp.find(num) != temp.end())
        {
            temp.erase(num);
            cnt ++;
            if(dir)
            {
                num ++;
            }
            else
            {
                num --;
            }
        }
        
        return cnt;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值