[js] 选择数组中两数和与目标值对相等,优化算法提升效率
#
//timeout var sum_pairs1 = function(ints, s) { var l = ints.length, temp = [], least = 10000000; for (var i = 0; i < l - 1; i++) { for (var j = i + 1; j < l; j++) { if (ints[i] + ints[j] == s && j - i < least) { least = j - i; temp[0] = ints[i]; temp[1] = ints[j]; } } } if (temp.length > 0) { return temp; } else { return undefined; } } //hash var sum_pairs2 = function(ints, s) { var seen = {} for (var i = 0; i < ints.length; ++i) { //console.info(s,ints[i],s-ints[i]); if (seen[s - ints[i]]) { return [s - ints[i], ints[i]]; } seen[ints[i]] = true //console.log(seen); } } //利用 while 、 break、indexOf var sum_pairs3 = function(ints, s) { var i = 0; var tried = []; var pairIndex1 = []; var pairIndex2 = []; var arrayLen = ints.length; while (i < arrayLen) { if (tried.indexOf(ints[i]) === -1) { for (var j = i + 1; j < arrayLen; j++) { if (ints[i] + ints[j] === s) { pairIndex1.push(i); pairIndex2.push(j); break; } } tried.push(ints[i]); //console.info(tried); } i++; } //console.log(pairIndex1, pairIndex2); if (pairIndex1.length === 0) { return undefined; } else if (pairIndex1.length === 1) { return [ints[pairIndex1[0]], ints[pairIndex2[0]]]; } else { var lowestIndexInInts = Math.min.apply(null, pairIndex2); var posInPairs = pairIndex2.indexOf(lowestIndexInInts); return [ints[pairIndex1[posInPairs]], ints[lowestIndexInInts]]; } } //不稳定的写法 var sum_pairs4 = function(ints, s) { ints = remove_duplicates(ints); //console.log(ints); for (var i = 1; i < ints.length; i++) { for (var j = 0; j < i; j++) { if (ints[j] + ints[i] === s) { return [ints[j], ints[i]]; } } } return undefined; }; var remove_duplicates = function(ints) { //去重 return ints.reduce(function(acc, current) { if (acc.length === 0 || acc[acc.length - 1] !== current) { acc.push(current); return acc; } else { return acc; } }, []); }; //other var sum_pairs = function(ints, s) { var res = [ints.length, ints.length]; var maps = []; for (var i = 0; i < ints.length; i++) { if (maps[s - ints[i]]) { return [s - ints[i], ints[i]]; } maps[ints[i]] = [i]; //console.log(maps); } }
l1 = [1, 4, 8, 7, 3, 15]; l2 = [1, -2, 3, 0, -6, 1]; l3 = [20, -13, 40]; l4 = [1, 2, 3, 4, 1, 0]; l5 = [10, 5, 2, 3, 7, 5]; l6 = [4, -2, 3, 3, 4]; l7 = [0, 2, 0]; l8 = [5, 9, 13, -3]; sum_pairs(l1, 8); sum_pairs(l2, -6); sum_pairs(l3, -7); sum_pairs(l4, 2); sum_pairs(l5, 10); sum_pairs(l6, 8); sum_pairs(l7, 0); sum_pairs(l8, 10);
```
function sum_pairs(ints, s) {
let seen = new Set();
for (let i of ints) {
if (seen.has(s - i)) return [s - i, i];
seen.add(i);
}
}
```