/*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.*/
#include <vector>
#include <unordered_set>
#include <algorithm>
#include <iostream>
class Solution
{
public:
int longestConsecutive(std::vector<int>& num)
{
if(num.size()==0)
return 0;
std::unordered_set<int> set;
int longest=0;
int cc=0;
std::for_each(num.begin(),num.end(),[&](const int& val)
{
set.insert(val);
}
);
std::for_each(num.begin(),num.end(),[&](const int& val)
{
if(set.find(val)==set.end()) ;
else
{
cc=1;
set.erase(val);
for(int tv=val+1;;++tv)
{
if(set.find(tv)!=set.end())
{
最长连续序列(O(n),C++版)
最新推荐文章于 2022-05-02 22:37:28 发布
该博客介绍了如何使用C++在O(n)的时间复杂度内找到一个未排序整数数组中最长的连续元素序列。通过使用`unordered_set`存储数组元素并遍历,找到连续序列并更新最长长度。例如,对于输入[100, 4, 200, 1, 3, 2],最长连续序列是[1, 2, 3, 4],其长度为4。"
119523215,1477485,WPF控件解析:Canvas深度探究,"['wpf', '图形绘制', '用户界面设计', '动画效果', '布局']
摘要由CSDN通过智能技术生成