Javascript 使用while循环查找连续数字的最长子数组
我想用while语句编写一个函数,该语句确定正整数数组中最大连续子数组的长度。至少有一个连续数组。例如:Javascript 使用while循环查找连续数字的最长子数组,javascript,Javascript,我想用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循环和另一个“array lengthing”方法,不确
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循环和另一个“array lengthing”方法,不确定它是如何调用的,请参见下文
我的尝试:
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语句,并使用更新的变量从失败的位置重新开始。它还将初始化另一个值为1的数组索引,该索引随后将使用if语句进行更新
最后,我有一个类似于[1,2,3]的反数组,其中3代表最大的连续子数组。感谢大家阅读本文或帮助像我这样的初学者更深入地理解Javascript。您可以采取一种方法,只计算长度,并检查最大查找长度(如果是连续项) 函数长子输入{ 设i=1,//省略第一个元素,并在此索引之前使用后面的元素 最大值=0, tempLength=1;//使用一个初始化 if!input.length返回0; 而我
const max_slices =
xs =>
xs.reduce
( (a, b) =>
a.length > b.length
? a
: b
);
max_slices(slices([6, 7, 8, 6, 12, 1 ,2 ,3, 4, 5]));
//=> [1, 2, 3, 4, 5]
下面是一个使用while循环的简单解决方案: 设arr=[6,7,8,6,12,1,2,3,4] 设endIndx=0,maxLength=0,indx=1,tempMax=0; 而indx
如果maxLength,您想获得连续子数组的长度或值吗?@Nina,谢谢您的回答。我刚刚用输入[6,7,8,6,12,1,2,3,4,5]尝试了您的解决方案它应该返回5,因为它返回了1,2,3,4,5。也许我应该给出一个更好的输入示例,对此表示抱歉。@customcommander,谢谢您的帮助。我想知道您是否可以在第一个函数中添加一两条注释,因为它很漂亮,但对我来说也有点难理解。
const max_slices =
xs =>
xs.reduce
( (a, b) =>
a.length > b.length
? a
: b
);
max_slices(slices([6, 7, 8, 6, 12, 1 ,2 ,3, 4, 5]));
//=> [1, 2, 3, 4, 5]