JavaScript——找出数组连续和为指定sum的开始和结束索引

在看问答区时看到这样的一个问题:
“已知一个包含n个数字的数组A,其中连续多个数字的和为sum,请找出该连续数字的初始索引start和结束索引end”
当然,你可以使用嵌套循环来解决,我这里提供一个使用一个循环解决的方法,目前我测试是没有问题的,分享出来,如果有不适用的例子请大家留言

const arr1 = [7,5,4,3,1,2,3,4,5,6,0]    //测试1
const arr2 = [1,2,3,4,5,6,7,8,9,0]      //测试2
const arr3 = [10]                       //测试3
const arr4 = [12,23,1,2,3,4,5,6,7]      //测试4
const sum = 10                          //测试5

function findIndex(arr,sum){
    let tempSum = 0;	//临时sum
    let backIndex = 0;	//回跳索引
    let endIndex = -1;	//结束索引
    let currentIndex = 0;	//当前索引
    for(currentIndex; currentIndex<arr.length; currentIndex++){
        tempSum+=arr[currentIndex];
        if(sum<tempSum){
            backIndex += 1;
            currentIndex = backIndex;
            tempSum = 0;
        }else if(sum == tempSum){
            endIndex = currentIndex;
            break;
        }
    }
    if(endIndex==-1){
        console.log("没有找到")
    }else{
        console.log("startIndex:",backIndex==0?0:backIndex+1);
        console.log("endIndex:",endIndex);
    }
}
//执行测试
findIndex(arr4,sum);

整体思路就是在循环外面设定几个值:临时和、当前索引、回跳索引、结束索引。通过循环叠加临时和,如果临时和大于指定sum,这时需要将回跳索引加1,并且将回跳索引值赋值给当前索引,知道临时和等于指定和则跳出循环,在输出结果时需要注意,如果回跳索引如果为0那么起始索引就是0,否则是回跳索引加1,如果结束索引为-1则表示没有找到符合的连续元素。

posted @ 2022-06-02 08:39  胡海龙  阅读(46)  评论(0)    收藏  举报
www.huhailong.vip