【发布时间】:2025-11-26 21:45:01
【问题描述】:
我想编写一个带有 while 语句的函数,用于确定正整数数组中最大连续子数组的长度。 (至少有一个连续的数组。)例如:
Input: [6, 7, 8, 6, 12, 1, 2, 3, 4] --> [1,2,3,4]
Output: 4
Input: [5, 6, 1, 8, 9, 7] --> [1,8,9]
Output: 3
通常我稍后会尝试使用 for 循环和 array.push 方法,但是,为了获得更多练习,我想使用 while 循环和另一种“数组延长”方法,不知道它是如何调用的,见下文。
我的尝试:
function longestSub (input) {
let i=0;
let idx=0;
let counterArr=[1]; //init. to 1 because input [4,5,3] equals sub-length 2
while(i<input.length) {
if (input[i]+1 > input[i]) {
counterArr[0+idx] += 1
}
else {
i=input.indexOf(input[i]); //should start loop at this i-value again
idx +=1;
counterArr[0+idx] = 1; //should init new array index
}
i++
}
return Math.max(...counterArr)
}
我的想法是,else 语句会在 if 语句失败时重置 if 语句,并使用更新的变量从失败的位置重新开始。它还将使用值 1 初始化另一个数组索引,随后使用 if 语句进行更新。
最后我有一个类似 [1,2,3] 的 counterArr,其中 3 代表最大的连续子数组。感谢大家阅读本文或帮助像我这样的初学者更深入地了解 Javascript。
【问题讨论】:
-
你想只获取连续子数组的长度还是值?
标签: javascript