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));
添加回答
舉報