欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > LeetCode 力扣 热题 100道(十九)最长连续序列(C++)

LeetCode 力扣 热题 100道(十九)最长连续序列(C++)

2025/5/14 22:53:09 来源:https://blog.csdn.net/weixin_64593595/article/details/144447545  浏览:    关键词:LeetCode 力扣 热题 100道(十九)最长连续序列(C++)

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

class Solution {
public:int longestConsecutive(vector<int>& nums) {unordered_set<int> numSet(nums.begin(), nums.end()); int longestStreak = 0;for (int num : numSet) {if (numSet.find(num - 1) == numSet.end()) {int currentNum = num;int currentStreak = 1;while (numSet.find(currentNum + 1) != numSet.end()) {currentNum++;currentStreak++;}longestStreak = max(longestStreak, currentStreak);}}return longestStreak;}
};
  • 去重:首先将输入的数组 nums 转换为哈希集合 numSet,这样就去除了重复的元素,并且能够在常数时间内检查元素是否存在。
  • 查找最长连续序列
    • 对于每一个数字 num,我们检查 num - 1 是否存在于集合中。如果不存在,说明 num 是某个连续序列的起始元素。
    • 然后从 num 开始,逐个检查 num + 1, num + 2, ... 是否存在于集合中,直到遇到不存在的元素。
  • 更新最长序列长度:在每次查找完一个序列后,更新 longestStreak 以记录目前为止找到的最长连续序列的长度。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词