简体   繁体   中英

Iterate array and find the sum between a range of numbers

例如,如果我通过数字10和阵列[1, 2, 4, 4]的函数应该如果阵列是[4,2,1,1]的函数应返回假,因为总和2之间不数字。

Use #some and #find functions to check if the sum of any two numbers in the given array equals the passed argument - see demo below:

 function solution(num, array) { return array.some(function(e, i) { return (num - e + array.find(function(c, k) { return c == e && i != k })) == num; }); } console.log(solution(8, [-1, 2, 3, 4]), solution(8, [-1, 4, 3, 4]), solution(8, [4,3,45,2,5,3])); 

I would solve it like this with no recursion, just looping over the elements and the next ones and exit the loop as soon as a solution is found:

 function solution(n, arr) { if (n < 0) return null; if (n === 0) return []; for (var i = 0; i < arr.length; i++) { var first = arr[i]; // first addend for (var j = i + 1; j < arr.length; j++) { // considering only next elements in the array if (first + arr[j] === n) { console.log(`found solution with ${first} and ${arr[j]}`); return true; } } } console.log('no solution found'); return false; } console.log(solution(8, [4, 3, 45, 2, 5, 3])); console.log(solution(8, [-1, 2, 3, 4])); 

The naive implementation for checking for a sum of two numbers is a nested loop, see below:

function isSumInArray(sum, array) {
    for (let i=0; i < array.length; i++) {
        for (let j=0; j < array.length; j++) {
            if (array[i] + array[j] === sum && i !== j) {
                return true 
            }
        }
    }
    return false;
}

There are better ways to implement this, but I'm choosing it because I think it's the most simplistic to understand. You're going through the array twice here, and if the two numbers are equal to your desired sum (and they are not the same number in the array), then return true. If none of the combinations satisfy this condition, return false.

for any tow numbers in array

 function test(array , n) { for(var i=0;i<array.length;i++) { for(var j=0;j<array.length ; j++) if(array[i] + array[j] == n && i != j) return true; } return false; } var array = [1,2,3,4,2]; console.log(test(array , 1)); console.log(test(array , 4)); 

For each element, you need to "do the math" with every other element to see if they sum correctly.

The simplest implementation is a nested loop O(N^2).

Pseudocode:

def solution(list, target)
  for each element e1 in list
    for each element e2 in list
      if e2 is e1 
        continue
      end if
      if e1 + e2 is target
        return true
      end if
    loop
  loop
  return false
end def

Code:

 function solution(list, target) { for(let i = 0; i < list.length; i++) { const e1 = list[i]; for(let j = 0; j < list.length; j++) { const e2 = list[j]; if(i === j) { continue; } if(e1 + e2 === target) { return true; } } } return false; } console.log(solution([1,2,3,4,5], 2)); 

The next simplest solution is to realise that addition (ie. the sum operation) is commutative. This means that the order of the operands does not matter. 1+2 is the same as 2+1. This means that we need not re-calculate the sums for numbers we have already visited in the outer loop because as we advance we calculate the sum for a + b and by definition therefore cover b + a. The overall complexity remains the same though: O(N^2) (AFAICT).

Pseudocode:

def solution(list, target)
  for each element e1 in list
    for each element e2 that is to the right of e1 in list
      if e1 + e2 is target
        return true
      end if
    loop
  loop
  return false
end def

Code:

 function solution(list, target) { for(let i = 0; i < list.length; i++) { const e1 = list[i]; for(let j = i+1; j < list.length; j++) { const e2 = list[j]; if(e1 + e2 === target) { return true; } } } return false; } console.log(solution([1,2,3,4,5], 5)); 

A better solution is to combine the two facts that addition is commutative and that we know what to look for without having to actually enumerate the list a second time. ie if a is the current element, then we know we want a + x = target so x can be easily calculated (it is the difference). By using an O(1) lookup data structure we can replace the inner loop and make the algorithm O(N) overall.

To re-state the problem, each element in the list must be summed with all the elements to the left and all those to the right. As we advance with the outer loop we perform the summing for all right-hand elements (because of the commutativity of addition). All elements to the right of an element will eventually be tested with it as the loop advances.

To sum with all the elements to the left we can replace the inner loop with a hash table indexed by the elements seen already. We can then use the fact that a + x = target , therefore, x = target - a to check for the presence of x in the hash table.

Pseudocode:

def solution(list, target)
  var hash <- hashtable: [integer:boolean]
  for each element in list
    if hash has sum-element
      return true
    else
      add element to hash
    endif 
  loop
end def

Code:

 function solution(list, target) { const hash = new Set; for(let e of list) { if(hash.has(target-e)) { return true; } hash.add(e); } return false; } solution([1,2,3,4,5], 3); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM