比如有1,2,5,6,7,11,14这组号码,怎么过滤出[1,2]和[5,6,7]这两组号码?求指点
2 回答
呼唤远方
TA贡献1856条经验 获得超11个赞
这种逻辑?vararr=[1,2,5,6,7,11,14];varlen=arr.length,before=arr[0],i=1,res=[],result=[],current;for(;icurrent=arr[i]; if(current-before===1){if(res.length===0)res.push(before);res.push(current);}else{if(res.length){result.push(res);}res=[];}before=current;}if(res.length){result.push(res);}console.log(result);
互换的青春
TA贡献1797条经验 获得超6个赞
这样行吗?functionsubsequence(arr){if(!arr||arr.length<2)return[];letresult=[],curr=arr[0],subArr=[curr];for(leti=1;iif(arr[i]===curr+1){ subArr.push(arr[i]);curr=arr[i];}else{if(subArr.length>1){result.push(subArr);}curr=arr[i];subArr=[curr];}}if(subArr.length>1){result.push(subArr);}returnresult;}//testconsole.log(subsequence([]));console.log(subsequence([0]));console.log(subsequence([1,2,5,6,7,11,14]));console.log(subsequence([1,2,3,4,7,8,9,11,23,45,56,66,67]));console.log(subsequence([9,8,7,7,8,9,0]));
添加回答
举报
0/150
提交
取消