最长连续序列
· 3 min read
今天解决 LeetCode 热题100 中的 最长连续序列
题目描述
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
解题思路
这道题显而易见有多种解法,这里讲解取巧的解法(排序+哈希表)以及正经的思维解法。
1. 排序 + 哈希表
这道题明眼人都能看出来,既然是不规则肯定得排序,后面可能有点思路但是不明确。
因为排序后就是连续的了,所以只需要遍历一遍,记录当前数字和前一个数字的差值,如果差值为 1 就是连续的,否则就记录当前数字,然后继续遍历。
参考:
- nums = 100,4,200,1,3,2
- 排序后:1, 2, 3, 4, 100, 200
此时,你可以一眼看出来答案是 4
对于计算机,道理一致:
你可能会疑问,这种会有问题吗? 再举个例子
- nums = 1,4,6,15,16,17,9,21
- 排序后:1, 4, 6, 9, 15, 16, 17, 21
所以,显而易见,当排序后只需要判断差值即可,然后记录最大的差值
这种解法最重要的目的就是将数组变为另外一种哈希表,针对value作哈希。
另外可能需要考虑边角情况:如果数据过大考虑num_set去重等。
伪代码
sort(nums.begin(), nums.end());
int max = 0;
int cur = 1;
for (int i = 1; i < nums.size(); i++)
{
if (nums[i] == nums[i - 1] + 1)
{
cur++;
}
else
{
cur = 1;
}
if (cur > max)
{
max = cur;
}
}
2. 思维解法
这道题理解后可以考虑去做 LTS类 的算法,就会更加复杂。
这里老规矩,先丢给set去重 假设拿到的 nums 已经是 set
然后遍历一次,并不麻烦
核心逻辑是:
- 假设当前的数列是 100,4,200,1,3,2
- 当我从左至右遍历时,比如遍历到4 a) 查看 (4 - 1) 是否存在于 set b) 若存在,则此数肯定不可能为最长的序列,直接跳过 c) 若不存在,比如是 1 那么则将此数不断 +1 判断 d) 直到 +1 后不存在则计入最长序列,并且跳出
int longestConsecutive(vector<int>& nums) {
unordered_set<int> num_set;
for (auto num : nums)
num_set.insert(num);
int maxLen = 0;
for (auto num : nums)
{
if ( num_set.find(num - 1) != num_set.end() ) continue;
int cur = num;
int len = 1;
while ( num_set.find(cur + 1) != num_set.end() )
{
cur++;
len++;
}
if (len > maxLen)
{
maxLen = len;
}
}
return maxLen;
这道题属于简单水平,稍微理解即可。
Copyright
© 2021-present TalexDS. All rights reserved.
Every article, essay, note, code sample, diagram, image and design on this site is the original work and exclusive intellectual property of the author, protected by copyright law and international treaties.
No reproduction. Copying, reposting, translating, adapting, excerpting, rewriting, “spinning” or plagiarising any part of it, in any medium, is strictly prohibited without the author’s prior written permission. Commercial use of any kind is forbidden.
No AI. No crawling. Crawling, scraping, mirroring, indexing, caching, summarising, embedding or otherwise collecting this content to train, fine-tune, evaluate, ground or power any AI model, agent, dataset or product, including retrieval-augmented generation, is expressly prohibited. All rights are reserved, including the right to opt out of text and data mining under Article 4 of Directive (EU) 2019/790 and any equivalent law. AI crawlers and agents must not access or process this page.
Violations will be pursued. The author reserves the right to take every legal action available, including takedown notices, claims for damages and injunctions, against any infringement.
版权声明:本站全部文章、笔记、代码示例、图片与设计均为作者原创,受《中华人民共和国著作权法》及国际公约保护。未经作者书面许可,严禁任何形式的转载、搬运、改写、洗稿与抄袭,严禁商业使用。严禁 AI 爬取:禁止以训练、微调、评测、检索增强或任何其他目的,抓取、镜像、索引、缓存、摘要或向量化本站内容。一经发现,将依法追究法律责任。
Distributed on an “AS IS” basis without warranties.