当前位置:网站首页>最长连续序列[扩散法+空间换时间]
最长连续序列[扩散法+空间换时间]
2022-06-24 21:17:00 【REN_林森】
扩散法+空间换时间
前言
空间换时间核心是为了降低时间复杂度,但有时候是解题的关键,毕竟时间有限(先双指针一样)。
典型的空间换时间就是数组/数组hash/hash。
本文通过最长连续序列来感受空间换时间,并练习扩散法。
一、最长连续序列

二、扩散法+空间换时间
package everyday.medium;
import java.util.HashSet;
import java.util.Set;
// 最长连续序列
public class LongestConsecutive {
/* target:找到里面最长连续数字,如果排个序,直接O(n)遍历一遍记录到最长即可。 但是时间复杂度要求O(n),所以只能空间换时间,先用hash存起来,方便后面快速查找(以扩散法查找)。 */
public int longestConsecutive(int[] nums) {
// 特殊情况,特殊处理。
if (0 == nums.length) return 0;
Set<Integer> set = new HashSet<>();
// 准备工作,记录所有元素,并赋初值为1,表示连续个数1。
for (int n : nums) if (!set.contains(n)) set.add(n);
// 遍历nums,求相邻的元素的总连续度。
int ans = 1;
// 扩散法,每个值最多被访问两次,一次有,一次无。
for (int n : nums) {
// 没有用过的数字,才从两边扩散开来。
if (set.contains(n)) {
// 开始往两边扩散,扩散法。
int len = 1;
int left = n, right = n;
while (set.contains(--left)) {
++len;
set.remove(left);
}
while (set.contains(++right)) {
++len;
set.remove(right);
}
// 取每次能扩散的最大长度。
ans = Math.max(ans, len);
}
}
return ans;
}
}
总结
1)空间换时间
2)扩散法
参考文献
[1] LeetCode 最长连续序列
边栏推荐
- Redis and jedis
- 天书夜读笔记——反汇编引擎xde32
- MySQL multi condition matching fuzzy query
- 音频PCM数据计算声音分贝值,实现简单VAD功能
- excel 汉字转拼音「建议收藏」
- Use redis' sorted set to make weekly hot Reviews
- Welcome to the new world of Lenovo smart screen
- 4 years of working experience, and you can't tell the five communication modes between multithreads. Can you believe it?
- 脱氧核糖核酸酶I中英文说明书
- void* 指针
猜你喜欢
随机推荐
为猪脸识别而进行自己数据集的构建、训练「建议收藏」
Matlab rounding
弹性蛋白酶中英文说明书
Basic knowledge of assembly language (2) -debug
Using bindservice method to pause music playing
void* 指针
Bi SQL drop & alter
Ideas and examples of divide and conquer
Transform BeanUtils to achieve list data copy gracefully
汇编语言(2)基础知识-debug
Which securities company should I choose to open an account online? Is it safe to open an account online?
利用 Redis 的 sorted set 做每周热评的功能
实验5 8254定时/计数器应用实验【微机原理】【实验】
论文翻译 | RandLA-Net: Efficient Semantic Segmentation of Large-Scale Point Clouds
Mysql database Chapter 1 Summary
Bi-sql - different join
php easywechat 和 小程序 实现 长久订阅消息推送
Install mysql5.6 under linux64bit - the root password cannot be modified
Novice, let me show you the "soft test" at one time
Bi skill - judge 0 and null









