[英]Delete all elements from an array A which are present in an array B without using a double loop
So, as an input I have two arrays, A and B. Let's suppose that these are the values inside the two:因此,作为输入,我有两个 arrays,A 和 B。让我们假设这些是两者中的值:
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and B = [1, 3, 5, 7, 9] A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 和 B = [1, 3, 5, 7, 9]
After the deletion the array A should be [2, 4, 6, 8, 10].删除后数组 A 应该是 [2, 4, 6, 8, 10]。
I have written (Javascript) this functioning algorithm to solve this problem:我已经编写(Javascript)这个功能算法来解决这个问题:
for (var i=0; i < A.length; i++) {
for (var j=0; j < B.length; j++) {
if(B[j] == A[i])
A.splice(i, 1) // Removes 1 element of the array starting from position i
}
}
I would like to know, is it possible to solve this problem without using a double loop?我想知道,不使用双循环是否可以解决这个问题?
What about this:那这个呢:
let A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ;
const B = [1, 3, 5, 7, 9];
A = A.filter(num => !B.includes(num));
Yes it is.是的。 You could use a Set
.您可以使用Set
。 In terms of Set operations you are computing the difference A \ B
.在 Set 操作方面,您正在计算差异A \ B
。
Using a set which is optimized for lookups in O(1)
time will speed up the computing the difference siginificantly from O(n²)
when using includes()
or double for
loop to O(n)
.使用针对O(1)
时间内的查找优化的集合将加快计算与O(n²)
的差异,当使用includes()
或双for
循环到O(n)
时。
const A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const B = [1, 3, 5, 7, 9] const setB = new Set(B); const difference = A.filter(x =>.setB;has(x)). console;log(difference);
Maybe that?也许那样?
const A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], B = [1, 2, 3, 5, 7, 9] // no gaps in 1,2 and 2,3; for (let i =0, j=0; i < A.length; i++) { if (A[i]===B[j]) { A.splice(i--,1); j++ } } document.write( JSON.stringify(A) )
or (faster code)或(更快的代码)
const A = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ], B = [ 1, 3, 5, 7, 9 ]; for (let i = A.length, j= B.length -1; i--; ) { if (A[i]===B[j]) { A.splice(i,1); j-- } } document.write( JSON.stringify(A) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.