我正在尝试在Codewar网站上实现名为“对的和”()的算法。我已经写了一个算法,但它没有通过所有的测试,它需要大量的时间来处理。请你建议我如何正确有效地解决这个问题。谢谢!
指示如下
sum_pairs([11, 3, 7, 5],         10)
#              ^--^      3 + 7 = 10
== [3, 7]
sum_pairs([4, 3, 2, 3, 4],         6)
#          ^-----^         4 + 2 = 6, indices: 0, 2 *
#             ^-----^      3 + 3 = 6, indices: 1, 3
#                ^-----^   2 + 4 = 6, indices: 2, 4
#  * entire pair is earlier, and therefore is the correct answer
== [4, 2]
sum_pairs([0, 0, -2, 3], 2)
#  there are no pairs of values that can be added to produce 2.
== None/nil/undefined (Based on the language)
sum_pairs([10, 5, 2, 3, 7, 5],         10)
#              ^-----------^   5 + 5 = 10, indices: 1, 5
#                    ^--^      3 + 7 = 10, indices: 3, 4 *
#  * entire pair is earlier, and therefore is the correct answer
== [3, 7]我的代码是:
var sum_pairs=function(ints, s){
    var total = 0;
    var list = [];
    for (var i=0; i < ints.length; i++) {
      for (var j=1; j < ints.length; j++) {
          total = ints[i]+ints[j];
          if (total === s) {
            list.push(ints[i], ints[j]); 
            return list;
        }  
        //console.log(total);
      }
    }
}
sum_pairs([1,2,3,4,1,0], 2);而且它没有通过这个测试:
✘ First Match From Left REDUX!: [10,5,2,3,7,5] should return [3, 7] for sum = 10发布于 2017-03-02 11:15:09
如果需要10M元素数组,则不能使用O(N^2)算法。下面的代码如何?
var sum_pairs=function(ints, s, und){
    var h = {}
    for(var i=ints.length - 1; i >= 0; --i){
      h[ints[i]] = i
    }
    for(var i=0; i < ints.length; ++i){
      var ci = ints[i]
      var e = h[s - ci]
      if(e < i){
        return [s - ci, ci]
      }
    }
    return und
}https://stackoverflow.com/questions/42551366
复制相似问题