Longest Consecutive Sequence

Problem Statement

  • 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.

 


 

There's a easy O(nlogn) solution.

 

We will define a hash table mp, and we initialize the hash table with 1:

1
2
3
unordered_map<int, int> mp;
for(int i = 0; i < n; ++i)
    mp[A[i]] = 1;

 

The value of mp, mp[A[i]] just means the maximum length of consecutive sequence in which the maximum element is A[i].

So at beginning, every element itself is a consecutive element, and the maximum length of consecutive sequence ended by A[i] is 1.

Then, for each element A[i] in A, we search its one less element A[i]-1. If it exists, we add the mp[A[i]], i.e.

1
++mp[A[i]]

Beacause the map is ordered by A[i], these operations can gurantee the increment of mp[A[i]] is beginning at the minimum element. Thus the algorithm is correct.

 


The O(n) solving method:

Our algorithm is to abstract every connected component(consecutive sequence) out of array A.

For every element A[i]Ci=[Cmin,Cmax]A, we search it from A[i] to its upper bound Cmax, and search it to its lower bound Cmin.

We first use a hash table to store every element in A as key. And we use true as this key's entry.

1
2
3
unordered_map<int, bool> mp;
for(int i = 0; i < length; ++i)
    mp[num[i]] = true;

 

Then, every time we access one element A[i], we erase it from mp, because it's one element of connected component Ci. Then we find if A[i+1] is exsiting in mp. If it is, we erase it from mp, and add the length of Ci, ++lenCi. And keep going until we can't find the next bigger element in mp.

1
2
3
4
5
6
7
8
9
int consecutiveLength = 1;  //A[i] itself is a consecutive sequence
int findNum = A[i];
mp.erase(findNum);
 
while(mp.find(mp[findNum+1]) != mp.end()){
    ++consecutiveLength;
    ++findNum;  //make findNum pointer to next bigger element
    mp.erase(findNum);
}

Then, we search to the lower bound of Ci from A[i] with the same method.

1
2
3
4
5
6
findNum = A[i];
while(mp.find(findNum-1) != mp.end()){
    ++consecutiveLength;
    --findNum;  //make findNum pointer to next smaller element
    mp.erase(findNum);
}

If the current consecutive length is bigger than sum before, we update the sum.

So, based on the above statement, we can iterate through the array to abstract every connected component out of array A. With the constraint of running time O(n), each time we access the element A[i], we only do the search we A[i] is still in mp.

 


 The complete code is below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
int longestConsecutive(vector<int> &num) {
    int length = num.size();
    if(0 == length) return 0;
     
    unordered_map<int, bool> mp;
    for(int i = 0; i < length; ++i){
        mp[num[i]] = true;
    }
     
    int res = 0;
    for(int i = 0; i < length; ++i){
        if(mp.find(num[i]) == mp.end()) continue;
         
        int consecutiveLength = 1;
        int findNum = num[i];
         
        mp.erase(findNum);
         
        while(mp.find(findNum+1) != mp.end()){
            ++consecutiveLength;
            ++findNum;
            mp.erase(findNum);
        }
         
        findNum = num[i];
        while(mp.find(findNum-1) != mp.end()){
            ++consecutiveLength;
            --findNum;
            mp.erase(findNum);
        }
         
        res = consecutiveLength > res ? consecutiveLength : res ;
    }
     
    return res;
     
}

 

posted @   kid551  阅读(136)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示