当前位置:网站首页>最长连续序列[扩散法+空间换时间]
最长连续序列[扩散法+空间换时间]
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 最长连续序列
边栏推荐
猜你喜欢
The latest QQ wechat domain name anti red PHP program source code + forced jump to open

Danish Technical University pioneered the application of quantum computing to power flow modeling of energy system

Bi-sql create

汇编语言(4)函数传参

程序员:是花光积蓄在深圳买房?还是回到长沙过“富余”生活?

How to store dataframe data in pandas into MySQL

实验5 8254定时/计数器应用实验【微机原理】【实验】

4年工作經驗,多線程間的5種通信方式都說不出來,你敢信?

动手学数据分析 数据建模和模型评估

15.线程同步的几种方法
随机推荐
Go language operators (under Lesson 8)
This national day! Tencent cloud wecity will accompany you to travel and light up the city landmark
Tencent moved!
云开发技术峰会·公益编程挑战赛【火热报名中】!
Tencent cloud wecity solution
Bi SQL drop & alter
JVM directive
Assembly language (4) function transfer parameters
汇编语言(4)函数传参
sql 聚合函数有哪些
Why does Dell always refuse to push the ultra-thin commercial notebook to the extreme?
Is it reliable to open an account on the flush with a mobile phone? Is there any hidden danger in this way
Bi SQL constraints
腾讯搬家了!
C language boundary calculation and asymmetric boundary
Basic knowledge of assembly language (2) -debug
pbcms添加循环数字标签
利用 Redis 的 sorted set 做每周热评的功能
15.线程同步的几种方法
弹性蛋白酶中英文说明书