首页 > 其他 > 详细

【Leetcode】Longest Consecutive Sequence

时间:2014-03-17 03:39:28      阅读:442      评论:0      收藏:0      [点我收藏+]

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.

数据元素无序但要求时间复杂度O(n)应联想到hash.

stl中unordered_map(c++ 11) 和 hash_map 速度比map(红黑树实现)快。新的标准推荐用unordered_map代替hash_map。

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         unordered_map<int, bool> table;
 5         for (auto i : num) {
 6             table[i] = false;
 7         }
 8         int ret = 0;
 9         for (auto i : num) {
10             if (table[i]) continue;
11             table[i] = true;
12             int len = 1;
13             for (int j = i + 1; table.find(j) != table.end(); ++j) {
14                 ++len;
15                 table[j] = true;
16             }
17             for (int j = i - 1; table.find(j) != table.end(); --j) {
18                 ++len;
19                 table[j] = true;
20             }
21             if (len > ret) ret = len;
22         }
23         return ret;
24     }
25 };
View Code

【Leetcode】Longest Consecutive Sequence,布布扣,bubuko.com

【Leetcode】Longest Consecutive Sequence

原文:http://www.cnblogs.com/dengeven/p/3603946.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!