Longest Consecutive Sequence(leetcode)

来源:互联网 发布:sqlserver 进阶 编辑:程序博客网 时间:2024/06/03 19:16

题目:

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.

题目来源:https://oj.leetcode.com/problems/longest-consecutive-sequence/

解题思路:参考的《leetcode题解》,利用hash表来节省时间。先初始化为false,然后没加入一个数就变成true,详情见代码,很好理解。

#include<iostream>#include<vector>#include<unordered_map>using namespace std;int longestConsecutive(vector<int> &num){if(num.empty())return 0;const int N=num.size();int longestNum=0,currLongest=0;unordered_map<int,bool> umap;for(int i=0;i<N;i++)umap[num[i]]=false;for(int i=0;i<N;i++){if(umap[num[i]]==true)continue;umap[num[i]]=true;currLongest=1;for(int j=num[i]+1;umap.find(j)!=umap.end();j++){umap[j]=true;currLongest++;}for(int j=num[i]-1;umap.find(j)!=umap.end();j--){umap[j]=true;currLongest++;}longestNum=max(currLongest,longestNum);}return longestNum;}int main(){int A[]={100, 4, 200, 1, 3, 2};vector<int> num(A,A+6);cout<<longestConsecutive(num)<<endl;system("pause");return 0;}


0 0
原创粉丝点击