LeetCode(128) 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.
分析
给定一个整形数组,求出最长的连续序列。例如数组[100,4,200,1,3,2],最长的连续序列长度为[1,2,3,4],长度为4。要求时间复杂度为O(n)。
首先,想到的办法就是 排序—>得到最长连续长度;但是不符合要求的时间复杂度,所以不予采用。
其次,第二个方法是利用c++中的set,直接会排序,并且没有重合的,但是set背后实现的原理牵扯到红黑树,时间复杂度同样不满足。
所以,解决该问题还是应该从哈希入手,建立hash索引,把查找的元素周围的都访问个遍,求出个临时最大值跟全局最大值比较。当再次访问该段的元素的时候,直接跳过。这样保证时间复杂度为O(n)。
c++11中数据结构为unordered_set,保证查找元素的时间复杂度为O(1),但是奇怪的是我才用的unordered_set并没有通过,给出的结果是TLE,于是,我就改用了unordered_map最后通过测试。
AC代码
class Solution {
public:
//方法一:使用unordered_set
int longestConsecutive1(vector<int>& nums) {
if (nums.empty() || nums.size() == 1)
return nums.size();
//保存序列元素个数
int size = nums.size();
unordered_set<int> existNums, visitedNums;
for (int i = 0; i < size; ++i)
{
existNums.insert(nums[i]);
}
int maxCount = 0;
for (int i = 0; i < size; ++i)
{
//每个连续序列中的元素只需要遍历一次,只有不在已遍历序列中时,向两侧探查
if (visitedNums.find(nums[i]) != visitedNums.end())
continue;
int count = 1, less = nums[i] - 1, great = nums[i] + 1;
while (existNums.find(less) != existNums.end())
{
visitedNums.insert(less);
++count;
--less;
}//while
while (existNums.find(great) != existNums.end())
{
visitedNums.insert(great);
++count;
--less;
}//while
if (count > maxCount)
maxCount = count;
}//for
return maxCount;
}
//方法二:使用unordered_map
int longestConsecutive(vector<int>& nums) {
if (nums.empty() || nums.size() == 1)
return nums.size();
//保存序列元素个数
int size = nums.size();
unordered_map<int, bool> visitedNums;
for (int i = 0; i < size; ++i)
{
visitedNums[nums[i]] = false;
}
int maxCount = 0;
for (int i = 0; i < size; ++i)
{
//若已访问过,则跳过
if (visitedNums[nums[i]])
continue;
int count = 1;
//改变访问标记
visitedNums[nums[i]] = true;
int less = nums[i] - 1, great = nums[i] + 1;
while (visitedNums.find(less) != visitedNums.end())
{
visitedNums[less] = true;
--less;
++count;
}//while
while (visitedNums.find(great) != visitedNums.end())
{
visitedNums[great] = true;
++great;
++count;
}//while
if (count > maxCount)
maxCount = count;
}//for
return maxCount;
}
};
LeetCode(128) Longest Consecutive Sequence的更多相关文章
- [LeetCode] 298. Binary Tree Longest Consecutive Sequence 二叉树最长连续序列
Given a binary tree, find the length of the longest consecutive sequence path. The path refers to an ...
- [LeetCode] 549. Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之 II
Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree. Especia ...
- LeetCode 549. Binary Tree Longest Consecutive Sequence II
原题链接在这里:https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/description/ 题目: G ...
- LeetCode 298. Binary Tree Longest Consecutive Sequence
原题链接在这里:https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/ 题目: Given a binary t ...
- [LeetCode] 549. Binary Tree Longest Consecutive Sequence II_ Medium tag: DFS recursive
Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree. Especia ...
- LeetCode (32) Longest Valid Parentheses
题目 Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
- LeetCode(5)Longest Palindromic Substring
题目 Given a string S, find the longest palindromic substring in S. You may assume that the maximum le ...
- LeetCode(3)Longest Substring Without Repeating Characters
题目: Given a string, find the length of the longest substring without repeating characters. For examp ...
- LeetCode(14)Longest Common Prefix
题目 Write a function to find the longest common prefix string amongst an array of strings. 分析 该题目是求一个 ...
随机推荐
- 062 Unique Paths 不同路径
机器人位于一个 m x n 网格的左上角, 在下图中标记为“Start” (开始).机器人每次只能向下或者向右移动一步.机器人试图达到网格的右下角,在下图中标记为“Finish”(结束).问有多少条不 ...
- python实现批量远程执行命令及批量上传下载文件
#!/usr/bin/env python # -*- coding: utf- -*- # @Time : // : # @Author : xuxuedong # @Site : # @File ...
- Appium基础二:Appium的安装(基Windows)
1.JAVA环境配置: 1.1安装jdk: 1.2配置JAVA_Home.Path配置.java验证 Path: 输入C:\Program Files\Java\jdk1.8.0_121\bin:C: ...
- Redis数据库1
一.启动服务 #进入redis安装文件夹 cd /usr/local/redis/ #开启服务端(后端开启) ./bin/redis-server ./redis.conf #开启客户端 ./bin/ ...
- linux下设置SSH无密码登录
ssh配置 主机A:10.0.5.199 主机B:10.0.5.198 需要配置主机A无密码登录主机A,主机B 先确保所有主机的防火墙处于关闭状态. 在主机A上执行如下: 1. $cd ~/.ssh ...
- UVALive 3942 Remember The Word (Tire)
状态是DAG,因此方案用dp统计,dp[i] = sum(dp[i+len(x)]),x是以i开头的前缀且是单词,关键在于快速判断一个前缀是不是单词,可用Trie. 每一次转移的复杂度是O(maxle ...
- Android(java)学习笔记112:Activity中的onCreate()方法分析
1.onCreate( )方法是android应用程序中最常见的方法之一: 翻译过来就是说,onCreate()函数是在activity初始化的时候调用的,通常情况下,我们需要在onCreate()中 ...
- git clone 和 download 不一样,能用git clone 就用git clone,download的代码,经常出现安装bug
git clone 和 download 不一样,能用git clone 就用git clone,download的代码,经常出现安装bug
- epoch,iteration,batch,batch_size
epoch:训练时,所有训练图像通过网络训练一次(一次前向传播+一次后向传播):测试时,所有测试图像通过网络一次(一次前向传播).Caffe不用这个参数. batch_size:1个batch包含 ...
- volatile引发的一系列血案
最早读<深入理解java虚拟机>对于volatile部分就没有读明白,最近重新拿来研究并记录一些理解 理解volatile前需要把以下这些概念或内容理解: 1.JMM内存模型 2.并发编程 ...