2014.1.13 19:00
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.
Solution:
I've seen this problem at the interview of NetEase before. Back then I discussed about an O(n * log(n)) algorithm wit my friends.
The solution uses a map to record the occurrence of each number. For a number N in the sequence, we scan the map to see if N - 1, N -2, .... and N + 1, N + 2, ... are in the sequence. From that we know the length of the longest consecutive sequence contain N.
To avoid repeated searches in the map, we'll use another map to mark each element as "already scanned" when they're found in the map.
For instance, the sequence [3, 1, 2] will produce result 3. It doesn't you start searching from 1, 2 or 3, because you always get [1, 2, 3] at last.
Like the following:
1: [] 1 [2, 3]
2: [1] 2 [3]
3: [1, 2] 3
Thus we can mark all consecutive elements as "already scanned" to avoid searching them again in the map. That saves some time indeed.
Although stl map is quite elegant and optimized, it is still O(log(n)) for every search action. So I chose unordered_map from C++11, which has an ammortized O(1) time complexity for insert and search action.
It is the difference between a hash-table and a red-black tree that decides their difference in time complexity level.
Time and space complexity are both O(n).
Accepted code:
1 // 1AC, excellent!!! 2 #include <unordered_map> 3 using namespace std; 4 5 class Solution { 6 public: 7 int longestConsecutive(vector<int> &num) { 8 // IMPORTANT: Please reset any member data you declared, as 9 // the same Solution instance will be reused for each test case. 10 int res, max_res; 11 unordered_map<int, int> a, b; 12 13 a.clear(); 14 b.clear(); 15 16 int n = num.size(); 17 if(n <= 0){ 18 return 0; 19 } 20 21 int i, j; 22 for(i = 0; i < n; ++i){ 23 a[num[i]] = 1; 24 } 25 26 max_res = 0; 27 for(i = 0; i < n; ++i){ 28 res = 0; 29 if(b.find(num[i]) != b.end()){ 30 continue; 31 } 32 b[num[i]] = 1; 33 ++res; 34 j = num[i] - 1; 35 while(a.find(j) != a.end() && b.find(j) == b.end()){ 36 b[j] = 1; 37 ++res; 38 --j; 39 } 40 j = num[i] + 1; 41 while(a.find(j) != a.end() && b.find(j) == b.end()){ 42 b[j] = 1; 43 ++res; 44 ++j; 45 } 46 47 if(res > max_res){ 48 max_res = res; 49 } 50 } 51 52 a.clear(); 53 b.clear(); 54 55 return max_res; 56 } 57 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)