设为首页 加入收藏

TOP

leetcode - Longest Consecutive Sequence
2015-07-20 17:34:58 来源: 作者: 【 】 浏览:1
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

评论

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

·Java 并发工具类:提 (2025-12-25 20:25:44)
·Java面试技巧:如何 (2025-12-25 20:25:41)
·Java并发编程中的线 (2025-12-25 20:25:38)
·C 语言 - cppreferen (2025-12-25 19:50:27)
·《C 语言入门教程》 (2025-12-25 19:50:23)