Longest Consecutive Sequence [LeetCode]

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.

Summary: The key idea is using hash map to record every number and their index.

 1     int longestConsecutive(vector<int> &num) {
 2         unordered_map<int, int> num_idx;
 3         for(int i = 0; i < num.size(); i ++) {
 4             num_idx[num[i]] = i;
 5         }
 6         
 7         vector<bool> visited;
 8         for(int i = 0; i < num.size(); i ++) {
 9             visited.push_back(false);
10         }
11         
12         int longest_len = 0;
13         for(int i = 0; i < num.size(); i ++) {
14             if(visited[i] == true)
15                 continue;
16                 
17             int tmp_len = 1;
18             visited[i] = true;
19             //increase
20             int value = num[i] + 1;
21             while(num_idx.find(value) != num_idx.end()){
22                 int index = num_idx[value];
23                 value ++;
24                 visited[index] = true;
25                 tmp_len ++;
26             }
27             //decrease
28             value = num[i] - 1;
29             while(num_idx.find(value) != num_idx.end()){
30                 int index = num_idx[value];
31                 value --;
32                 visited[index] = true;
33                 tmp_len ++;
34             }
35             
36             if(tmp_len > longest_len){
37                 longest_len = tmp_len;
38                 if(longest_len > num.size() / 2)
39                     break;
40             }
41         }
42         
43         return longest_len;
44     }

 

转载于:https://www.cnblogs.com/guyufei/p/3414035.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值