比较两个数组的有效方法 [英] Efficient way to compare two arrays
问题描述
我正在使用两个数组来完成一项检查array2中是否存在array1中的值的任务.如果是这样,请删除array1中的内容,并继续检查直到array1为空.如果它们不存在,则从函数中返回.我正在使用Javascript
I am using two arrays to accomplish a task of checking if values in array1 exist in array2. If so remove the content in array1 and keep checking till array1 is empty. If they dont exist just return from the function. I am using Javascript
我使用经典的两个for循环来实现它,其运行时间为o(n * 2).我想知道是否有其他有效的方法可以使用javascript支持的任何其他数据结构来执行此操作.下面是我当前的实现方式
I implemented it using classic two for loops which gives a run time of o(n*2). I would like to know if there is any other efficient way to perform this operation using any other data structure that javascript supports. Below is my current implementation
for(var j = 0; j < tempArray.length; j++){
for(var k = 0; k < this.probsSolved.length; k++){
if(tempArray[j] == this.probsSolved[k]){
tempArray.splice(j,1);
if(tempArray.length <= 0){
this.updateAchievements(achID);
this.storage.set(achKey,1);
return;
}
}
}
问题是我必须调用每5秒执行一次此操作的函数,这对我来说效率很低.
The thing is I have to call the function under which this operation is performed every 5 seconds and this for me looks highly inefficient.
有人可以建议一种比我可以使用的算法或数据结构更好的算法或数据结构,如果可以的话,我将如何使用.
Could someone suggest a better algorithm or a data structure that performs better than the one above that I can use and how would I use if so.
推荐答案
将 array2
的元素放入字典数据结构(以确保快速查找)可能会有所帮助.
Putting the elements of array2
in a dictionary data-structure (to ensure that lookup is quick) might help.
在伪代码中,我将采用以下方式:
In pseudo-code, I would approach like the following:
dict = {}
foreach elem in array2:
insert elem in dict
foreeach elem in array1:
if elem in dict:
remove elem from array1
这篇关于比较两个数组的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!