0

有一个数组[1,1,1,2,3,4,5,8,10,22,24,25,26,66]
请写一个方法把数组变成[1,1,[1,2,3,4,5],8,10,22,[24,25,26],66]
就是里面的顺着的数字归成一个数组,没思路,有没有好的方案?

查看全部 6 个回答

0

php版,菜鸟的想法:

`<?php 
 $arr = [1,1,1,2,3,4,5,8,10,22,24,25,26,66];
 $new_arr = '';
 foreach($arr as $k => $v){
    if($k == 0){
        $new_arr .= $v;
    }else{
        if($arr[$k-1]+1 == $v){
            $new_arr .= ",".$v;
        }else{
            $new_arr .= "#".$v;
        }
    }
 }
 $new_arr_1 = explode("#",$new_arr);
 foreach($new_arr_1 as $k1 => $v1){
    if(strpos($v1,",") !== false){
        $new_arr_2 = explode(",",$v1);
        $new_arr_1[$k1] = $new_arr_2;
    }
 }
 print_r($new_arr_1);
?>`

推荐答案

2

已采纳

两个指针 i,j

var arr = [1,1,1,2,3,4,5,8,10,22,24,25,26,66]
var len = arr.length
var i = 1, j = 0
var rst = []
for(; i <= len; i++) {
  if(arr[i]-arr[i-1] !== 1) {
    i-j===1 ? rst.push(arr[j]) : rst.push(arr.slice(j, i))
    j = i
  }
}