使用 map 函数代替嵌套循环条件 JS
Using a map function instead of a nested loop condition JS
我有以下函数,它接受一个数字数组和一个目标值,如果可以添加数组中的任何 2 个数字来给出目标值,则函数 return 为真,如果不是,它 return 是错误的。例如,如果 array = [5,4,2,3,1] 且 target = 9,则函数应 return true 为 5+4=9。但是,如果 target = 10,该函数应该 return false,因为数组中没有 2 个数字可以相加得到 10。
function Solution(array,target) {
for (var i = 0;i<array.length;i++) {
for (var j=0;j!=i && j<array.length;j++) {
if (array[i] + array[j] == target) {
return true
}
}
}
return false
}
上述函数按预期工作,但我认为这不是一个好方法,有人可以告诉我使用地图函数的更有效方法吗?
您可以采用散列 table 并将所需的增量作为键。
这种方法只需要一次迭代。
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
您可以维护一个 Set
以提高效率。
当您在数组中遇到新数字时,从目标总和中减去该数字。这将告诉您需要与当前数字相加才能达到目标总和的金额。您可以使用 .has()
检查 number/amount 是否在 O(1) 的集合中。如果它在集合中,您可以 return 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));
这是使用数组某种方法的简单一行解决方案。
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));
我有以下函数,它接受一个数字数组和一个目标值,如果可以添加数组中的任何 2 个数字来给出目标值,则函数 return 为真,如果不是,它 return 是错误的。例如,如果 array = [5,4,2,3,1] 且 target = 9,则函数应 return true 为 5+4=9。但是,如果 target = 10,该函数应该 return false,因为数组中没有 2 个数字可以相加得到 10。
function Solution(array,target) {
for (var i = 0;i<array.length;i++) {
for (var j=0;j!=i && j<array.length;j++) {
if (array[i] + array[j] == target) {
return true
}
}
}
return false
}
上述函数按预期工作,但我认为这不是一个好方法,有人可以告诉我使用地图函数的更有效方法吗?
您可以采用散列 table 并将所需的增量作为键。
这种方法只需要一次迭代。
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
您可以维护一个 Set
以提高效率。
当您在数组中遇到新数字时,从目标总和中减去该数字。这将告诉您需要与当前数字相加才能达到目标总和的金额。您可以使用 .has()
检查 number/amount 是否在 O(1) 的集合中。如果它在集合中,您可以 return 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));
这是使用数组某种方法的简单一行解决方案。
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));