Longest Consecutive Sequence

来源:互联网 发布:淘宝上传宝贝数据包 编辑:程序博客网 时间:2024/06/10 18:41

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.

这道题一开始想先排序,然后找,但是时间复杂度超过O(n). 参考了网上的资料,思路如下:

1.将原数组存到hash_set里面。因为查找时间复杂度O(1).

2.遍历数组,每次在hash表里面找它的+1和-1,找到连续的数,则往该方向(+1或者-1方向)继续找连续数。

3.统计+方向和-方向的连续数的个数即为所求。

int getNum(set<int> &map, int cur, bool up){    int num = 0;    while(map.find(cur) != map.end())    {        map.erase(cur);        num++;        up?cur++:cur--;    }    return num;}int longestConsecutive(vector<int> &num){    set<int> map;    for(int i = 0; i < num.size(); ++i)        map.insert(num[i]);    int max = 1;    for(int i = 0; i< num.size(); ++i)    {        if(map.find(num[i]) != map.end())        {            int temp = 1;            int cur = num[i];            map.erase(cur);            temp += getNum(map, cur + 1, true);            temp += getNum(map, cur - 1, false);            max = temp > max ? temp : max;        }    }    return max;}

0 0
原创粉丝点击