题目

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. 初学python,感受和C的不同

    从开始看Python到现在也有半个多月了,前后看了Python核心编程和Dive into Python两本书.话说半个月看两本,是个人都知道有多囫囵吞枣,这也是因为我暂时没有需求拿这个做大型开发,主 ...

  2. JavaScript_对象

    1.  直接创建实例: //简单对象 var person1 = new Object(); person1.name = "Mike"; person1.age = 29; pe ...

  3. LeetCode Remove Duplicates from Sorted List 删除有序链表中的重复结点

    /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode ...

  4. mustache.js 数组循环的索引

    在使用mustache作为模板引擎时,想要利用数组中的对象的索引排序,却发现mustache中无法获得数组索引,在一番搜索之后,发现在数组的对象中加入索引,就可以了,示例如下 /html {{#dat ...

  5. js在一个div里面移动其子div

    var ChildDiv = $("#cid"); var width = 0; //鼠标点击子div的地方和子div的左边边距距离 var height = 0; //鼠标点击子 ...

  6. IOS tableView 去除分割线 和 不允许选中表格cell

    //去除分割线 self.tableView.backgroundColor=[UIColor colorWithRed:///255.0 alpha:1.0]; self.tableView.sep ...

  7. hdu1150&&POJ1325 Machine Schedule---最小点覆盖

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1150 题目大意: 给你两台机器A和B,A机器有n种模式,B机器有m种模式,初始时都是0,现在给你k个 ...

  8. 【BZOJ1965】[AHOI2005] SHUFFLE 洗牌(数学题)

    点此看题面 大致题意: 有一叠扑克牌编号为\(1\sim n\)(\(n\)为偶数),每次洗牌将扑克牌平均分成上下两叠,取下面一叠的第一张作为新的一叠的第一张,然后取上面一叠的第一张作为新的一叠的第二 ...

  9. 2017.12.19 Java包的静态导入import static和import的区别

    import static静态导入是JDK1.5中的新特性.一般我们导入一个类都用 import com-..ClassName;而静态导入是这样:import static com-..ClassN ...

  10. STM32启动流程

    启动文件主要工作: . 设置堆栈指针SP=_initial_sp . 设置PC指针=Reset_Handler . 配置系统时钟 . 配置外部SRAM用于程序变量等数据存储(可选) . 调用C库中的_ ...