我尝试在 Codewars 网站上实施名为对的总和的算法。我编写了一个算法,但它没有通过所有测试,需要花费大量的时间来处理。请你能建议我如何正确有效地解决它。谢谢!
说明如下
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
答案 0 :(得分:3)
尝试此代码,适用于所有情况。 编辑:我只进行了一次循环解析,并使用了一个哈希。这是比以前更好的解决方案。运行时间约为5000毫秒。尝试浏览此线程以了解有关此逻辑的更多信息:Link
var sum_pairs=function(arr, num){
var len=arr.length,i,j,hash = {},first_index,second_index;
for(i=0;i<len;i++){
var looking_for = num - arr[i]
if(looking_for in hash){
first_index = hash[looking_for];
second_index = i;
return [arr[first_index], arr[second_index]];
}
hash[arr[i]] = i;
}
}
答案 1 :(得分:2)
如果您期望10M元素的数组,则不能使用O(N ^ 2)算法。下面的代码如何:
std::chrono::time_point
答案 2 :(得分:1)
现在有了一些超速机制,比如
a
的array[i]
长列表 153 ms 。
var sum_pairs = function (array, s) {
var a, i,
hash = Object.create(null);
for (i = 0; i < array.length; i++) {
a = array[i];
if (hash[s - a]) {
return [s - a, a];
}
if (!hash[a]) {
hash[a] = true;
}
}
};
console.log(sum_pairs([11, 3, 7, 5], 10)); // [3, 7]
console.log(sum_pairs([4, 3, 2, 3, 4], 6)); // [4, 2]
console.log(sum_pairs([0, 0, -2, 3], 2)); // undefined
console.log(sum_pairs([10, 5, 2, 3, 7, 5], 10)); // [3, 7]
console.log(sum_pairs([1, 2, 3, 4, 1, 0], 2)); // [1, 1]
console.log(sum_pairs([1, -2, 3, 0, -6, 1], -6)); // [0, -6]
console.log(sum_pairs([0, 2, 0], 0)); // [0, 0]
console.log(sum_pairs([5, 9, 13, -3], 10)); // [13, -3]
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 3 :(得分:0)
试试这个,
var sum_pairs=function(ints, s){
var total = 0;
var list = [];
//skip the last num
for (var i=0; i < ints.length-1; i++) {
//skip nums which is greater than s
if(ints[i]>=s){
continue;
}
//start from i+1
for (var j=i+1; j < ints.length; j++) {
total = ints[i]+ints[j];
if (total === s) {
list.push(ints[i], ints[j]);
return list;
}
//console.log(total);
}
}
}