雙指標查詢陣列的連續規律子陣列問題

看風景就發表於2018-07-19

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;
}

 

相關文章