当前位置:网站首页>LeetCode 128最长连续序列
LeetCode 128最长连续序列
2022-06-26 18:07:00 【Maccy37】
题目:给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
我的解:
class Solution {
public:
int max(int a,int b)
{
return a>b?a:b;
};
int longestConsecutive(vector<int>& nums) {
int size=nums.size();
if(size==0)
return 0;
sort(nums.begin(),nums.end());
int count=1,large=1;
for(int i=1;i<size;i++)
{
if((nums[i]-nums[i-1])==1)
{count++;}
else
{
large=max(large,count);
count=1;
}
}
return large;
}
};
正确解:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int mmax = 0;
for (int i = 0; i < nums.size(); i ++)
if (find(nums.begin(), nums.end(), nums[i] - 1) == nums.end()) { //未找到
int cnt = 1, num = nums[i];
while(find(nums.begin(), nums.end(), num + 1) != nums.end()) //找到了
cnt ++, num ++;
mmax = max(mmax, cnt);
}
return mmax;
}
};
编译结果:
我还没搞明白为什么我的是错的。
边栏推荐
猜你喜欢
next(iter(dataloader))的一点点体会
properties文件乱码
The difference between round and truncate in SQL (round or truncate)
Detailed explanation of asymmetric cryptosystem
vutils.make_grid()与黑白图像有关的一个小体会
RuntimeError: CUDA error: out of memory自己的解决方法(情况比较特殊估计对大部分人不适用)
wm_concat()和group_concat()函数
必须要掌握的面试重点——索引和事务(附讲B-树与B+树)
Digital signature standard (DSS)
wechat_ Solve the problem of page Jump and parameter transfer by navigator in wechat applet
随机推荐
决策树与随机森林
Tencent qianzhiming: Exploration and application of pre training methods in information flow business
Case study of row lock and isolation level
Rich professional product lines, and Jiangling Ford Lingrui · Jijing version is listed
Paging query and join Association query optimization
必须要掌握的面试重点——索引和事务(附讲B-树与B+树)
Padding percentage operation
How pycharm modifies multiline annotation shortcuts
数据加密标准(DES)概念及工作原理
Halcon's region: features of multiple regions (5)
JVM entry Door (1)
解决pycharm里面每个字母占一格空格的问题
Dos et détails de la méthode d'attaque
Regular match same character
9、智慧交通项目(2)
我想知道,我在肇庆,到哪里开户比较好?网上开户是否安全么?
Digital signature standard (DSS)
Detailed explanation of MySQL mvcc mechanism
数字签名论述及生成与优点分析
Decision tree and random forest