LeetCode-128. Longest Consecutive Sequence

网友投稿 553 2022-10-02

LeetCode-128. Longest Consecutive Sequence

LeetCode-128. Longest Consecutive Sequence

​​an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]Output: 4Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

题解:边界值坑死了。。。

class Solution {public: int longestConsecutive(vector& nums) { int n = nums.size(); if (n <= 1){ return n; } int ans = 1, l = 1; sort(nums.begin(), nums.end()); for (int i = 0; i < n - 1; i++){ if (nums[i] == nums[i + 1] - 1){ l++; } else if (nums[i] == nums[i + 1]){ continue; } else { l = 1; } ans = max(ans, l); } return ans; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:挖财-水仙花数
下一篇:小程序data-是什么(小程序data-index)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~