2 回答
TA贡献1846条经验 获得超7个赞
function two_sum(arr) {
let hash = new Map();
return arr.reduce((results, ele, i) => {
if (hash.has(-ele)) {
results = results.concat(hash.get(-ele).map(e => [i, e]))
}
hash.set(ele, hash.get(ele) || []);
hash.get(ele).push(i);
return results;
}, []);
}
TA贡献1783条经验 获得超4个赞
像这样的事情,也许:
const sumZeroIndexPairs = arr => {
const hashMap = arr.reduce(
(result, value, index, list) => {
list.forEach((n, i) => {
const key = [ index, i ].sort().join('_')
const sum = value + n
result[key] = sum
})
return result
},
{}
);
return Object.entries(hashMap)
.filter( ([key, value]) => value === 0 )
.map(([key]) => key.split('_'));
}
console.log(sumZeroIndexPairs([1, 2, 3, -1, 5, -5, 7, 9, -7, 2, -2]))
添加回答
举报