3 回答

TA贡献1871条经验 获得超13个赞
您可以采用一个以所需增量作为键的哈希表。
这种方法只需要一次迭代。
function solution(array, target) {
const seen = {};
for (const value of array) {
if (seen[value]) return true;
seen[target - value] = true;
}
return false;
}
console.log(solution([5, 4, 3, 2, 1], 9)); // true
console.log(solution([5, 4, 3, 2, 1], 10)); // false

TA贡献2080条经验 获得超4个赞
这是使用数组某种方法的简单一行解决方案。
const Solution = (array, target) =>
array.some((x, i) => array.some((y, j) => i !== j && x + y === target));
console.log(Solution([5, 4, 2, 3, 1], 9));
console.log(Solution([5, 4, 3, 2, 1], 10));
console.log(Solution([5, 4, 3, 2, 1], 5));

TA贡献1775条经验 获得超8个赞
您可以维护 aSet
来提高效率。
当您在数组中遇到新数字时,从目标总和中减去该数字。这将告诉您需要与当前数字相加的金额才能达到目标总和。您可以使用 O(1) 检查该数字/金额是否在集合中.has()
。如果它在集合中,您可以返回 true,否则,您可以将该数字添加到集合中以检查数组的进一步迭代。
请参阅下面的示例:
function solution(array, target) {
const set = new Set();
for(const num of array) {
if(set.has(target-num))
return true;
set.add(num);
}
return false;
}
console.log(solution([5,4,2,3,1], 9));
添加回答
举报