当前位置:网站首页>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;
}
};编译结果:

我还没搞明白为什么我的是错的。
边栏推荐
- wechat_微信小程序中解决navigator进行页面跳转并传递参数问题
- Paging query and join Association query optimization
- How does Guosen Securities open an account? Is it safe to open a stock account through the link
- transforms. The input of randomcrop() can only be PIL image, not tensor
- 我想知道,我在肇庆,到哪里开户比较好?网上开户是否安全么?
- How to open a stock account? Is it safe to open an account online now?
- RSA concept explanation and tool recommendation - LMN
- Applet setting button sharing function
- JVM入個門(1)
- RSA encryption and decryption details
猜你喜欢

贝叶斯网络详解

The king of Internet of things protocol: mqtt

分页查询、JOIN关联查询优化

深层次安全定义剖析及加密技术

transforms. The input of randomcrop() can only be PIL image, not tensor

transforms.RandomCrop()的输入只能是PIL image 不能是tensor

wechat_ Solve the problem of page Jump and parameter transfer by navigator in wechat applet

padding百分比操作

in和exsits、count(*)查询优化

pycharm如何修改多行注释快捷键
随机推荐
pycharm的plt.show()如何保持不关闭
[unity] use C in unity to execute external files, such as Exe or bat
利用递归实现求n位所有格雷码
How pycharm modifies multiline annotation shortcuts
MySQL的MVCC机制详解
Plt How to keep show() not closed
Properties file garbled
如何将应用加入到deviceidle 白名单?
In and exceptions, count (*) query optimization
transforms.RandomCrop()的输入只能是PIL image 不能是tensor
带你解决哈希冲突,并实现一个简单hash表,
Tencent qianzhiming: Exploration and application of pre training methods in information flow business
Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance!
RSA concept explanation and tool recommendation - LMN
Map and list < map > transfer to corresponding objects
How about opening an account at Guojin securities? Is it safe to open an account?
你了解如何比较两个对象吗
ISO文件
Temporarily turn off MySQL cache
How about opening an account at Guojin securities? Is it safe?