Find 2 numbers in an unsorted array equal to a given sum

前端 未结 18 938
太阳男子
太阳男子 2020-11-29 19:56

We need to find pair of numbers in an array whose sum is equal to a given value.

A = {6,4,5,7,9,1,2}

Sum = 10 Then the pairs are - {6,4} ,

18条回答
  •  猫巷女王i
    2020-11-29 20:15

    The following code returns true if two integers in an array match a compared integer.

     function compareArraySums(array, compare){
    
            var candidates = [];
    
            function compareAdditions(element, index, array){
                if(element <= y){
                    candidates.push(element);
                }
            }
    
            array.forEach(compareAdditions);
    
            for(var i = 0; i < candidates.length; i++){
                for(var j = 0; j < candidates.length; j++){
                    if (i + j === y){
                        return true;
                    }
                }
            }
        }
    

提交回复
热议问题