leecode---Longest Consecutive Sequence

本文介绍了一种寻找数组中最长连续元素序列的算法,通过使用哈希表存储元素并遍历查找相邻元素,实现了O(n)的时间复杂度。文章提供了详细的思路解析及C++代码示例。

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

这道题貌似在陈利人的微博上看到过,当时是有思路的:即采用hash的方法。但是再一次的看到的时候完全不知道怎么做了。

思路应该是这样的:先从头到尾建立hash,然后,从第一个值开始,++看看在不在里面,--看看在不在hash里面。如果在的话,计数,并继续前面的过程。查找完的数要删除掉。

代码同样未实现,下面是别人的代码:

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

转载于:https://www.cnblogs.com/kamendula/archive/2013/05/05/3061474.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值