码迷,mamicode.com
首页 > 其他好文 > 详细

【Longest Consecutive Sequence】cpp

时间:2015-04-17 23:40:26      阅读:127      评论: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.

 

代码

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        // hashmap record if element in num is visited
        std::map<int,bool> visited;
        for(std::vector<int>::iterator i = num.begin(); i != num.end(); ++i)
        {
            visited[*i] = false;
        }
        // search the longest consecutive
        unsigned int longest_global = 0;
        for(std::vector<int>::iterator i = num.begin(); i != num.end(); ++i)
        {
            if(visited[*i]) continue;
            unsigned int longest_local = 0;
            for(int j = *i+1; visited.find(j) != visited.end(); ++j)
            {
                visited[j] = true;
                ++longest_local;
            }
            for(int j = *i-1; visited.find(j) != visited.end(); --j)
            {
                visited[j] = true;
                ++longest_local;
            }
            longest_global = std::max(longest_global, longest_local+1);
        }
        return longest_global;
    }
};

 Tips:

1. 要想O(n), 而且无序,只能结合hashmap

2. 这里需要明确的一个逻辑是,通过hashmap前后访问,可以把包含当前元素的最大连同序列都找出来;而且访问过的元素不用再访问。

【Longest Consecutive Sequence】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4436279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!