【问题标题】:Find a pair of elements from an given array whose sum equals a specific target number in JavaScript从给定数组中找到一对元素,其总和等于 JavaScript 中的特定目标数
【发布时间】:2020-01-27 22:17:07
【问题描述】:

在 Javascript 中还有其他有效的方法来完成这项任务吗?

我试过了:

const a1 = [1,3,4,2,5,7,8,6];
var newArray =[];

function fun(a,n){      

for(let i = 0; i<a.length; i++){
 for(let j=i+1; j<a.length; j++){        
   if((a[i]+a[j])==n){        
     newArray.push([a[i],a[j]]);       
    }
  }
 }
}     

fun(a1, 10)
console.log(newArray);

这里输出:

[(3,7),(4,6),(2,8)]

【问题讨论】:

  • 非常广泛的问题。但如果我必须提出建议,我会说先对数组进行排序,然后从两端向中间工作

标签: javascript arrays function


【解决方案1】:

这个问题被标记为 javascript,但这个答案基本上与语言无关。

如果数组已排序(或者您可以对其进行排序),您可以遍历数组并为其中的每个元素 x 二进制搜索数组中的 (target-x)。这会给你 O(nlogn) 的运行时间。

如果您可以使用额外的内存,您可以使用数组的元素填充字典,然后为数组中的每个元素 x 查找字典 (target-x)。如果你的字典是在哈希表上实现的,这会给你 O(n) 的运行时间。

【讨论】:

  • 谢谢,但是你能不能通过写JS代码来详细说明一下。
【解决方案2】:

我认为从蛮力的角度来看你的方法是有意义的。

在优化方面,我想到了一些事情。

  1. 重复计算吗?如果没有,您可以从 起始名单。

  2. 您可以按升序对列表进行排序, 当总和超过 目标值。

【讨论】:

    【解决方案3】:

    这是一个一般的编程问题,通常被称为“二和问题”,它本身是subset sum problem 的一个子集。 但仍然可以有效地解决,我以this article 为灵感。

    const a1 = [1, 3, 4, 2, 5, 7, 8, 6];
    
    // our two sum function which will return
    // all pairs in the array that sum up to S
    function twoSum(arr, S) {
    
      const sums = [];
      const hashMap = new Map();
    
      // check each element in array
      for (let i = 0; i < arr.length; i++) {
    
        // calculate S - current element
        let sumMinusElement = S - arr[i];
    
        // check if this number exists in hash map
        // if so then we found a pair of numbers that sum to S
        if (hashMap.has(sumMinusElement.toString())) {
          sums.push([arr[i], sumMinusElement]);
        }
    
        // add the current number to the hash map
        hashMap.set(arr[i].toString(), arr[i])
      }
    
      // return all pairs of integers that sum to S
      return sums;
    }
    
    console.log(twoSum(a1, 10))

    这里我使用Map 对象,因为我认为检查数字是否已经存在时会更快,但我可能错了,如果你愿意,你可以只使用一个普通对象,如文章中所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多