找到数组的最大序列 | JavaScript
假设需要编写一个以数组为输入并返回不包含多于两个不同数字的最大数组序列的函数。如果仔细查看此问题,这涉及检查一个稳定的子数组和迭代原始数组。
因此,滑动窗口算法非常适合这个问题。通过滑动窗口算法解决此问题的代码如下 −
示例
const arr = [1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8, 1, 1 ,1 ,1, 8, 1,
1, 8, 8];
const map = {
length: 0
};
let required = [];
for(start = 0, end = 0; end <= arr.length; ){
if(map.length > 2){
if(map[arr[start]] === 1){
delete map[arr[start]];
map.length --;
}else{
map[arr[start]]--;
};
start++;
}else{
if(end - start > required.length){
required = arr.slice(start, end);
};
if(map[arr[end]]){
map[arr[end]]++;
}else{
map[arr[end]] = 1;
map.length++;
}
end++;
}
}
console.log(required);我们维护了一个映射来存储数组中任意点不同字符的计数,并在每次迭代中不断比较最长子数组的长度,当不同字符的计数超过 2 时,我们将数组向右滑动,寻找下一个稳定的数组。
输出
控制台中的输出将是 −
[ 1, 8, 1, 1, 1, 1, 8, 1, 1, 8, 8 ]
广告
数据结构
网络连接
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP