1. 查找连续重复的子数组
var arr = [1,2,3,9,9,9,9,6,7,9,9,9,8,10,10,10,15,10,10]; var fContinue1 = function(arr,start,end){ return arr[end+1] - arr[end] != 0 && end - start > 0; }, fForward1 = function(arr,start,end){ return arr[end+1] - arr[end] == 0; }; console.log(getResultCommon(arr,fContinue1,fForward1));
2. 查找连续等差的子数组
var arr = [1,2,3,9,10,11,12,6,7,9,9,9,8,10,11,12,15,19,20]; var fContinue2 = function(arr,start,end){ return arr[end+1] - arr[end] != 1 && end - start > 0 }, fForward2 = function(arr,start,end){ return arr[end+1] - arr[end] == 1 }; console.log(getResultCommon(arr,fContinue2,fForward2));
3. 查找连续等比子数组
var arr = [1,2,3,9,18,36,12,6,7,9,9,9,8,16,32,12,15,30,60]; var fContinue3 = function(arr,start,end){ return arr[end+1] / arr[end] != 2 && end - start > 0 }, fForward3 = function(arr,start,end){ return arr[end+1] / arr[end] == 2 }; console.log(getResultCommon(arr,fContinue3,fForward3));
4. 查找连续平方子数组
var arr = [1,2,3,9,81,11,12,6,2,4,8,64,8,10,11,4,16,256,10]; var fContinue4 = function(arr,start,end){ return arr[end+1] / arr[end] != arr[end] && end - start > 0 }, fForward4 = function(arr,start,end){ return arr[end+1] / arr[end] == arr[end]; }; console.log(getResultCommon(arr,fContinue4,fForward4));
通用的方法
/** * * @param arr 目标数组 * @param fContinue 检测双指针的位置是否符合条件,返回布尔值 * @param fForward 检测相邻值是否符合条件,快指针是否继续移动,返回布尔值 */ function getResultCommon(arr,fContinue,fForward){ var start = end = 0; var len = arr.length; var res = []; while(end < len + 1){ if(fContinue(arr,start,end)){ res.push([start,end]); end++; start = end; continue; } if(fForward(arr,start,end)){ end++; } else{ end++; start = end; } } return res; }