在一个无序整数数组中,找出连续增长片段最长的一段, 增长步长是1。Example: [3,2,4,5,6,1,9], 最长的是[4,5,6]
下面是我自己的编写的代码,感觉还能再优化。
希望有大神可以分享一下自己的解决方案
代码
let arr = [3,2,1,14,5,5,8,1,2,3,4,5,6,76,7,1,2,9];
function fn(arr){
let temp = [];
let sub = [];
for ( let i = 0; i < arr.length; i++ ){
if(arr[i]+1 === arr[i+1]){
temp.push(arr[i]);
}else{
if(temp.length!=0){
let temp1 = [];
temp.push(arr[i]);
for( let i = 0 ; i < temp.length; i++){
temp1.push(temp[i])
}
if(sub.length===0||sub.length<temp1.length){
sub = temp1
}
temp = [];
}
}
}
return sub;
}
let arr1 = fn(arr);
console.log(arr1);