当前位置:网站首页>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 .
边栏推荐
- Which securities company is better for a novice to open a stock trading account? How is it safer to speculate in stocks??
- 陈强:阿里千亿级大规模数字商业知识图谱助力业务增长
- [unity] use C in unity to execute external files, such as Exe or bat
- LeetCode 238 除自身以外数组的乘积
- vutils.make_grid()与黑白图像有关的一个小体会
- Decision tree and random forest
- ROS查询话题具体内容常用指令
- 17.13 补充知识、线程池浅谈、数量谈、总结
- 手写promise.all
- Li Kou daily question - day 28 -566 Reshape matrix
猜你喜欢
随机推荐
tag动态规划-刷题预备知识-2. 0-1背包理论基础和二维数组解法模板
50行代码爬取Top500图书导入TXT文档
新手炒股开户选哪个证券公司比较好?怎样炒股比较安全??
Please advise tonghuashun which securities firm to choose for opening an account? Is it safe to open an account online now?
next(iter(dataloader))的一点点体会
DoS及攻擊方法詳解
How about opening an account at Guojin securities? Is it safe to open an account?
RuntimeError: CUDA error: out of memory自己的解决方法(情况比较特殊估计对大部分人不适用)
pycharm如何修改多行注释快捷键
临时关闭MySQL缓存
同花顺开户怎么样安全吗?怎么炒股开户
Dos et détails de la méthode d'attaque
Deep understanding of MySQL lock and transaction isolation level
ROS的发布消息Publishers和订阅消息Subscribers
正则匹配相同字符
判断某个序列是否为栈的弹出序列
RSA加密解密详解
【NPOI】C#跨工作薄复制Sheet模板导出Excel
vutils.make_grid()与黑白图像有关的一个小体会
Chinese (Simplified) language pack