find pair of numbers in array that add to given sum

前端 未结 19 2194
萌比男神i
萌比男神i 2020-11-30 20:17

Question: Given an unsorted array of positive integers, is it possible to find a pair of integers from that array that sum up to a given sum?

Constraints: This shou

19条回答
  •  囚心锁ツ
    2020-11-30 20:48

    First you should find reverse array => sum minus actual array then check whether any element from these new array exist in the actual array.

    const arr = [0, 1, 2, 6];
    
    const sum = 8;
    
    let isPairExist = arr
      .map(item => sum - item) // [8, 7, 6, 2];
      .find((item, index) => {
        arr.splice(0, 1); // an element should pair with another element
        return arr.find(x => x === item);
      })
      ? true : false;
    
    console.log(isPairExist);
    

提交回复
热议问题