Enter an array and a number to determine whether the sum of three numbers in the array is equal to this number.

topic description

enter an array and a number to determine whether the sum of three numbers in the array is equal to this number

Sep.04,2021

var target=27;
var arr=[2,4,6,3,7,23,6,25,34,43,1,15,12,32,26,18,16];
for(var i=0;i<arr.length-3;iPP){
    for(var j=i+1;j<arr.length-2;jPP){
        for(var k=j+1;k<arr.length-1;kPP){
            if(arr[i]+arr[j]+arr[k]==target){
                return true;
            }
        }
    }
}

rewrote an algorithm:

var target=17;
var arr=[1,21,1,3,2,9,10,11,19,17,6,7,12,16,16,1];
arr=arr.sort();//[1,1,1,2,3,6,7,9,10,11,12,16,16,17,19,21]
for(var i=arr.length-1;i>1;i--){
    if(arr[i]>=target) continue;
    for(var j=0;j<i-1;jPP){
        if(arr[i]+arr[j]>=target) break;
        for(var k=j+1;k<i;kPP){
            var sum=arr[i]+arr[j]+arr[k];
            if(sum==target) return true;
            if(sum>target) break;
        }
    }
}
Menu