当前位置:网站首页>Leetcode 128 longest continuous sequence
Leetcode 128 longest continuous sequence
2022-06-26 18:13:00 【Maccy37】
subject : Given an array of unsorted integers , Find out the length of the longest continuous sequence .
The time complexity of the algorithm is required to be O(n).
Example :
Input : [100, 4, 200, 1, 3, 2]
Output : 4
explain : The longest continuous sequence is [1, 2, 3, 4]. Its length is 4.My solution :
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;
}
};Correct solution :
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()) { // Not found
int cnt = 1, num = nums[i];
while(find(nums.begin(), nums.end(), num + 1) != nums.end()) // eureka
cnt ++, num ++;
mmax = max(mmax, cnt);
}
return mmax;
}
};Compilation result :

I haven't figured out why mine is wrong .
边栏推荐
- Binary search-2
- Regular match same character
- 深入理解MySQL锁与事务隔离级别
- Ethereum技术架构介绍
- sql 中的alter操作总结
- MySQL download and configuration MySQL remote control
- Hello, is it safe to open an online stock account and buy stocks now?
- Case study of row lock and isolation level
- Handwritten promise all
- JS common regular expressions
猜你喜欢
随机推荐
17.13 supplementary knowledge, thread pool discussion, quantity discussion and summary
我想知道,我在肇庆,到哪里开户比较好?网上开户是否安全么?
pycharm的plt.show()如何保持不关闭
Handwritten promise all
Binary search-1
深入理解MySQL锁与事务隔离级别
gdb安装
Chinese (Simplified) language pack
ZCMU--1367: Data Structure
Please advise tonghuashun which securities firm to choose for opening an account? Is it safe to open an account online now?
贝叶斯网络详解
Procedure steps for burning a disc
KDD 2022 | 如何在跨域推荐中使用对比学习?
Data Encryption Standard DES security
vutils.make_grid()与黑白图像有关的一个小体会
Paging query and join Association query optimization
Temporarily turn off MySQL cache
[npoi] C copy sheet template across workbooks to export Excel
【NPOI】C#跨工作薄复制Sheet模板导出Excel
transforms. The input of randomcrop() can only be PIL image, not tensor









