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)
class Solution { public: int longestConsecutive(vector<int> &num) { int size=num.size(); if(size==0)return 0; //第一遍扫描建立前后关系map map<int, int> exist; for(int i=0; i<size; i++){ exist[num[i]]=1; if(exist[num[i]-1]!=1)exist[num[i]-1]=0; if(exist[num[i]+1]!=1)exist[num[i]+1]=0; } //第二遍扫描 int maxLength=0; for(int i=0; i<size; i++){ if(exist[num[i]]==1){ //恢复串 int length=1; int number=num[i]-1; while(exist[number]==1){length++; exist[number]=0; number--;} number=num[i]+1; while(exist[number]==1){length++; exist[number]=0; number++;} if(length>maxLength)maxLength=length; } } return maxLength; } };
LeetCode: Longest Consecutive Sequence [128],布布扣,bubuko.com
LeetCode: Longest Consecutive Sequence [128]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/34126555