longest-consecutive-sequence

来源:互联网 发布:淘宝网电子商务模式 编辑:程序博客网 时间:2024/06/11 01:43

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.

一开始使用位图排序,结果发现超出内存限制,后来根据提示使用哈希map,从每个数组中的值开始向前向后寻找,一直到找不到为止.并标记已经访问过的元素.

class Solution {public:    int longestConsecutive(vector<int> &num) {        if(num.size()<=1)            return num.size();       unordered_map<int,bool> mymap;       int sum=0;       for(int i=0;i<num.size();++i)           {           mymap.insert(make_pair(num[i],0));       }       int i=0;       while(i<num.size())           {           int temp=0;           int aft=num[i];           int bef=num[i];           if(mymap[num[i]]==0){           while(mymap.find(aft)!=mymap.end())               {               mymap[aft]=1;               ++temp;               ++aft;           }           while(mymap.find(bef)!=mymap.end())               {               mymap[bef]=1;               ++temp;               --bef;           }           if(temp>sum)                 sum=temp;           }                          ++i;                  }           return sum-1;//重复计算了一次     }};
0 0
原创粉丝点击