题目

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 = ;
for(std::vector<int>::iterator i = num.begin(); i != num.end(); ++i)
{
if(visited[*i]) continue;
unsigned int longest_local = ;
for(int j = *i+; visited.find(j) != visited.end(); ++j)
{
visited[j] = true;
++longest_local;
}
for(int j = *i-; visited.find(j) != visited.end(); --j)
{
visited[j] = true;
++longest_local;
}
longest_global = std::max(longest_global, longest_local+);
}
return longest_global;
}
};

Tips:

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

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

=======================================================

第二次过这道题,大体的思路能顺下来,但是疏忽了几个细节。AC代码如下:

class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int global_longest = 1;
// initialize map
unordered_map<int, bool> visited;
for ( int i=0; i<nums.size(); ++i ) visited[nums[i]]=false;
// go one traversal
for ( int i=0; i<nums.size(); ++i )
{
if ( visited[nums[i]] ) continue;
visited[nums[i]] = true;
int local_longest = 1;
int curr = nums[i]-1;
// search towards smaller direction
while ( visited.find(curr)!=visited.end() )
{
local_longest++;
visited[curr] = true;
curr--;
}
// search towards larger direction
curr = nums[i]+1;
while ( visited.find(curr)!=visited.end() )
{
local_longest++;
visited[curr] = true;
curr++;
}
// update global longest
global_longest = std::max(global_longest, local_longest);
}
return global_longest;
}
};

tips:

1. 根据某个元素往‘前’、‘后’两个方向遍历之前,要先记得把该元素设置为访问过(即,visited[nums[i]] = true;)

2. 第一遍把while循环中的 visited[curr]=true都写成了visited[nums[i]],这个纯属低级错误,不要再犯

3. 第一遍有一个逻辑上的错误:

  "for ( int i=0; i<nums.size() && !visited[nums[i]]; ++i )"

本意是跳过已经访问过的元素。。。但是这么写如果遇到了访问过的元素,就不是跳过了,而是直接退出循环了。这是个思维的陷阱,记下来,下次不要再犯。

【Longest Consecutive Sequence】cpp的更多相关文章

  1. 【Longest Common Prefix】cpp

    题目: Write a function to find the longest common prefix string amongst an array of strings. 代码: class ...

  2. 【Longest Palindromic Substring】cpp

    题目: Given a string S, find the longest palindromic substring in S. You may assume that the maximum l ...

  3. 【Longest Valid Parentheses】cpp

    题目: Given a string containing just the characters '(' and ')', find the length of the longest valid ...

  4. 【leetcode】Longest Consecutive Sequence

    Longest Consecutive Sequence Given an unsorted array of integers, find the length of the longest con ...

  5. 【LeetCode OJ】Longest Consecutive Sequence

    Problem Link: http://oj.leetcode.com/problems/longest-consecutive-sequence/ This problem is a classi ...

  6. 【LeetCode】128. Longest Consecutive Sequence

    Longest Consecutive Sequence Given an unsorted array of integers, find the length of the longest con ...

  7. [LeetCode] Binary Tree Longest Consecutive Sequence 二叉树最长连续序列

    Given a binary tree, find the length of the longest consecutive sequence path. The path refers to an ...

  8. [LeetCode] Longest Consecutive Sequence 求最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  9. Binary Tree Longest Consecutive Sequence

    Given a binary tree, find the length of the longest consecutive sequence path (连续的路径,不是从小到大). The pa ...

随机推荐

  1. Winform 读取 指定\另一个\其他\任意 配置文件

    ExeConfigurationFileMap map = new ExeConfigurationFileMap();            map.ExeConfigFilename = @&qu ...

  2. 软件测试Lab 1 Junit and Eclemma

    首先安装eclipse 然后下载hamcrest-core-1.3.jar,下载地址:http://mvnrepository.com/artifact/org.hamcrest/hamcrest-c ...

  3. echo -e的用法

    root@bt:~# echo -e "HEAD /HTTP/1.0\n\n"HEAD /HTTP/1.0 root@bt:~# echo -e "HEAD /HTTP/ ...

  4. 美国L-1A签证简介

    一. L-1A签证是美国非移民签证种类之一,主要发给外国跨国公司在美所设公司的高层管理人员.申请程序是先经美国移民局批准,美驻外使领馆凭移民局的批准函(I-797表)核发签证.移民局的批准函并不意味着 ...

  5. 基于spark Mllib(ML)聚类实战

        写在前面的话:由于spark2.0.0之后ML中才包括LDA,GaussianMixture 模型,这里k-means用的是ML模块做测试,LDA,GaussianMixture 则用的是ML ...

  6. 使用SAP云平台 + JNDI访问Internet Service

    以Internet Service http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Walldorf&destin ...

  7. World Wind Java开发之七——读取本地栅格文件(影像+高程)构建三维场景(转)

    http://blog.csdn.net/giser_whu/article/details/41679515 首先,看下本篇博客要达到的效果图: 下面逐步分析如何加载影像及高程文件. 1.World ...

  8. 【洛谷2468】[SDOI2010] 粟粟的书架(二合一)

    点此看题面 大致题意: 问你选取一个矩形区间内至少几个数,才能使它们的和\(\ge H_i\). 二合一 根据数据范围,比较显然能看出它是一道二合一的题目. 对于第一种情况,\(R,C\le 200\ ...

  9. 3204: 数组做函数参数--排序函数2--C语言

    3204: 数组做函数参数--排序函数2--C语言 时间限制: 1 Sec  内存限制: 128 MB提交: 211  解决: 143[提交][状态][讨论版][命题人:smallgyy] 题目描述 ...

  10. 2018.6.5 Oracle plsql编程 游标的使用

    --3.查询10部门所有员工的姓名.(ref游标实现) 动态游标 declare --创建一种游标类型 type type_cursor is ref cursor; --声明变量指定游标类型 v_c ...