我有两个对象数组。
Array1 : [{"id":20,"stName":"ABC","className":"A"},{"id":30,"stName":"ABD","className":"B"},{"id":40,"stName":"ABE","className":"C"},{"id":50,"stName":"ABF","className":"D"}]
Array2 : [{"id":110,"stName":"ASA","className":"X"},{"id":120,"stName":"ASB","className":"Y"},{"id":130,"stName":"ASC","className":"A"},{"id":140,"stName":"ASD","className":"C"},{"id":150,"stName":"ASE","className":"Z"}]
这里
array1将classNames设为A,B,C和D.
array2将classNames设为X,Y,A,C和Z
一个函数应返回classNames
array2
classNames
,array1
不属于javascript
函数的返回将是一个包含X,Y和Z作为元素的数组。
如何在时间复杂度较低的for loop
中编写此函数,因为array1和array2可能有20个以上的对象。
修改
这是我使用array1 = [{"id":20,"stName":"ABC","className":"A"},{"id":30,"stName":"ABD","className":"B"},{"id":40,"stName":"ABE","className":"C"},{"id":50,"stName":"ABF","className":"D"}]
array2 = [{"id":110,"stName":"ASA","className":"X"},{"id":120,"stName":"ASB","className":"Y"},{"id":130,"stName":"ASC","className":"A"},{"id":140,"stName":"ASD","className":"C"},{"id":150,"stName":"ASE","className":"Z"}]
function findSuggest(){
var sug = [];
for(array2_count=0;array2_count < array2.length;array2_count++){
for(array1_count=0;array1_count < array1.length;array1_count++){
if(array2[array2_count].className == array1[array1_count].className){
break;
}
else{
if(array1_count == (array1.length - 1)){
sug[sug.length] = array2[array2_count].className;
}
}
}
}
}
sug[]
此处{{1}}将提供所有建议。
答案 0 :(得分:19)
以下是该算法的一般概念:
Array1
。
className
添加到真值映射Array2
className
不在真实地图中,请将其添加到结果中。这很简单,O(n+m)
(最差情况O(2n)
)。通过真值图,我的意图是一个简单的js对象,其中每个键(在这种情况下)是className
,每个值都是true
。