设为首页 加入收藏

TOP

leetcode - Longest Consecutive Sequence
2015-07-20 17:34:58 来源: 作者: 【 】 浏览:2
Tags:leetcode 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(std::vector
  
    &num) {
		std::unordered_set
   
     a; std::unordered_set
    
      b; for (int i = 0; i < num.size(); i++) { a.insert(num[i]); } int max = 0; for (int i = 0; i < num.size(); i++) { if(b.find(num[i]) != b.end()) continue; int cnt = 1,n = num[i],m = num[i]; while(a.find(--n) != a.end()) b.insert(n),cnt++; while(a.find(++m) != a.end()) b.insert(m),cnt++; max = max > cnt ? max : cnt; } return max; } };
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇tips.Print的问题 下一篇01背包变形 HDU 2660

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)
·Redis配置中`require (2025-12-26 03:18:58)
·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)