leetcode Longest Consecutive Sequence
#include <iostream>
#include <vector>
#include <unordered_map>// 时间复杂度是O(n), 空间复杂度O(n)
using namespace std;class Solution1
{
public:int longestConsecutive(const vector<int> &nums){unordered_map<int, bool> used;for (auto i: nums) used[i] = false; // 自动匹配变量类型 建立一个 hash mapint longest=0;for (auto i:nums){if(used[i]) // truecontinue;int length=1;used[i] = true;for(int j=i+1; used.find(j) != used.end(); ++j){used[j] = true; // 向两边查找,找到了就置true,继续查找. 找不到就退出循环++length;}for (int j=i-1; used.find(j) != used.end(); --j){used[j] = true;++length;}longest = max(longest, length);}return longest;}
};int main()
{vector<int> nums={100, 4, 200, 1, 3, 2};Solution1 s;int length;length = s.longestConsecutive(nums);cout << length << endl;
}
转载于:https://www.cnblogs.com/o-v-o/p/9980307.html
leetcode Longest Consecutive Sequence相关推荐
- LeetCode: Longest Consecutive Sequence [128]
[题目] Given an unsorted array of integers, find the length of the longest consecutive elements sequen ...
- LeetCode:Longest Consecutive Sequence
题目链接 Given an unsorted array of integers, find the length of the longest consecutive elements sequen ...
- [LeetCode] Longest Consecutive Sequence 求解
为什么80%的码农都做不了架构师?>>> 题目 Given an unsorted array of integers, find the length of the long ...
- LeetCode: Longest Consecutive Sequence
想到map了,可惜没想到用erase来节省空间,看了网上答案 1 class Solution { 2 public: 3 int longestConsecutive(vector<int&g ...
- [leetcode]Longest Consecutive Sequence
这道题目一看就去翻答案了,因为以前见过,知道并查集可以用来做分组,但这样的题目真的要并查集么?想想也是HashSet之类就能搞定么.果然是HashMap而不是HashSet.下面这个解法我比较容易理解 ...
- 298. Binary Tree Longest Consecutive Sequence
题目: Given a binary tree, find the length of the longest consecutive sequence path. The path refers t ...
- leetcode 128. Longest Consecutive Sequence | 128. 最长连续序列(Java)
题目 https://leetcode.com/problems/longest-consecutive-sequence/ 题解 方法1:HashMap 解法,O(n^2) 如下图,假设 n=4 被 ...
- LeetCode 128. 最长连续序列(Longest Consecutive Sequence)
题目描述 给定一个未排序的整数数组,找出最长连续序列的长度. 要求算法的时间复杂度为 O(n). 示例: 输入: [100, 4, 200, 1, 3, 2] 输出: 4 解释: 最长连续序列是 [1 ...
- 128. Longest Consecutive Sequence
Title 给定一个未排序的整数数组,找出最长连续序列的长度. 要求算法的时间复杂度为 O(n). 示例: 输入: [100, 4, 200, 1, 3, 2] 输出: 4 解释: 最长连续序列是 [ ...
最新文章
- 语言兔子繁衍问题讲解_二年级思维数学:位置问题,找到重复部分是解题关键...
- centos7 通过脚本查询每个应用使用的内存
- Linux系统检测工具 三(Free,Top,ps,Vmstat,Sysstat)
- 面试ASP.NET程序员的笔试题和机试题
- 《TCP/IP详解》笔记----第二章 链路层
- 菜鸟学Java(六)——简单验证码生成(Java版)
- BizTalk开发系列(三十四) Xpath
- [leetcode] 96. 不同的二叉搜索树 +[补充] 不同的二叉树,不同形态的二叉树的个数----catalan数
- Bootstrap导航条
- Cell Ranger
- 为什么使用用友盟的摇一摇截屏功能,截出来的地图图片是黑屏的,渴求大师解答,感激不尽
- 西方文化系列讲座之罗马、基督教文化
- 无人机矿业地形图测量方案
- Debian改变网卡名称
- Java项目:考试在线报名管理系统(java+SSM+HTML+JS+jsp+mysql)
- Win10自动更新后,输入法故障问题
- discord Bot 实现机器人发送私信验证码
- 如何在Eero路由器上设置静态IP地址
- GB28181协议开发介绍
- 毕业论文答辩の七个原则(博士)