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

我还没搞明白为什么我的是错的。
边栏推荐
猜你喜欢
随机推荐
Data Encryption Standard DES security
二分查找-2
RuntimeError: CUDA error: out of memory自己的解决方法(情况比较特殊估计对大部分人不适用)
No manual prior is required! HKU & Tongji & lunarai & Kuangshi proposed self supervised visual representation learning based on semantic grouping, which significantly improved the tasks of target dete
JS cast
Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance!
Detailed explanation of MySQL mvcc mechanism
How does Guosen Securities open an account? Is it safe to open a stock account through the link
【QNX】命令
你好,现在网上股票开户买股票安全吗?
[code Capriccio - dynamic planning] t583. Deleting two strings
Vscode usage - Remote SSH configuration description
MySQL的MVCC机制详解
How pycharm modifies multiline annotation shortcuts
VCD video disc
#25class的类继承
Deep understanding of MySQL lock and transaction isolation level
pycharm的plt.show()如何保持不关闭
JS 常用正则表达式
ROS的发布消息Publishers和订阅消息Subscribers









