首页 > 代码库 > Longest Consecutive Sequence
Longest Consecutive Sequence
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.
class Solution { public: int longestConsecutive(vector<int> &num) { int n=num.size(); vector<int> v1; vector<int> v2; for(int i=0;i<n;i++) if(num[i]<0) v1.push_back(num[i]); else v2.push_back(num[i]); radixsort(v1); radixsort(v2); for(int i=0;i<v1.size();i++) num[i]=v1[v1.size()-i-1]; for(int i=0;i<v2.size();i++) num[i+v1.size()]=v2[i]; //get the longest int longest=1; int index=0; while(true) { if(index+1>=n) break; int con=1; int index2=index; while(index2+1<n && (num[index2+1]==num[index2] || num[index2+1]==num[index2]+1)) { if(num[index2+1]==num[index2]+1) con++; index2++; } if(con>longest) longest=con; index=index2+1; } return longest; } void radixsort(vector<int> &num) { int n=num.size(); int* data=http://www.mamicode.com/(int*)malloc(n*sizeof(int)); int d=1; int radix=10; int* bulk=(int*)malloc(radix*sizeof(int)); //radix sort for(int k=0;k<10;k++) { for(int i=0;i<radix;i++) bulk[i]=0; for(int i=0;i<n;i++) { int ibulk=num[i]/d%radix; if(ibulk<0) ibulk=-ibulk; bulk[ibulk]++; } int step=bulk[0]; bulk[0]=0; for(int i=1;i<radix;i++) { int step2=bulk[i]; bulk[i]=bulk[i-1]+step; step=step2; } for(int i=0;i<n;i++) { int ibulk=num[i]/d%radix; if(ibulk<0) ibulk=-ibulk; data[bulk[ibulk]]=num[i]; bulk[ibulk]++; } for(int i=0;i<n;i++) num[i]=data[i]; d=d*radix; } free(data); free(bulk); } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。