0
点赞
收藏
分享

微信扫一扫

CICD:github actions 实现CICD

Villagers 2023-10-15 阅读 57

文章目录

写在前面


Tag

【哈希表】【数组】


题目来源

128. 最长连续序列


题目解读

在无序数组中,找到最长的数字连续序列。要求时间复杂度为线性的。


解题思路

方法一:哈希表

要求的线性时间复杂度的解法,我们使用哈希集合来完成。

维护一个哈希集合,将数组中的所有元素加入到集合中;然后遍历集合中的数,统计这个数两头可以扩展到最大连续长度。

实现代码

class Solution {
public:
	int longestConsecutive(vector<int>& nums) {
		unordered_set<int> hash;
		for (int num : nums)
			hash.insert(num);

		int ans = 0;
		while (!hash.empty()) {
			int cur = *(hash.begin());
			hash.erase(cur);

			int next = cur + 1, prev = cur - 1;
			while (hash.count(next))
				hash.erase(next++);
			while (hash.count(prev))
				hash.erase(prev--);
			ans = max(ans, next - prev - 1);
		}
		return ans;
	}
};

复杂度分析

时间复杂度: O ( n ) O(n) O(n) n n n 为数组 nums 的长度。

空间复杂度: O ( n ) O(n) O(n),哈希集合占用了额外的


写在最后

如果文章内容有任何错误或者您对文章有任何疑问,欢迎私信博主或者在评论区指出 💬💬💬。

如果大家有更优的时间、空间复杂度方法,欢迎评论区交流。

最后,感谢您的阅读,如果感到有所收获的话可以给博主点一个 👍 哦。

举报

相关推荐

0 条评论