Finding the intersection of two arrays in Javascript [duplicate]

核能气质少年 提交于 2020-01-01 17:28:12

问题


This was an Amazon interview question I had an my answer was

function intersection ( A , B ) 
{
    var C = [];
    for ( var a in A ) if ( B.indexOf(a) != -1 ) C.push(a);
    return C;
}

and he asked what the order of complexity was and I said, and I quote exactly,

O(m * n) where m=A.length and n=B.length

and he was saying there's a better way to do it and I was like WTF??????? He was saying use A and B as Objects and I was like

"But you said these were arrays That was your question!!!!"

Can someone help me out here?


回答1:


If you know that the array values are strings or numbers, you can create an object that's got the values as property names and truthy values for each. Then you can use simple object lookup in a pass through the second array.

Something like:

function intersection ( A , B ) 
{
    var m = A.reduce(function(m, v) { m[v] = 1; return m; }, {});
    return B.filter(function(v) { return m[v]; });
}

edit — to remove duplicates from the result, another .reduce() pass could be used:

function intersection ( A , B ) 
{
    var m = A.reduce(function(m, v) { m[v] = 1; return m; }, {});
    return B.reduce(function(rv, v) {
      if (!rv.m[v]) {
        rv.m[v] = 1;
        rv.l.push(v);
      }
      return rv;
    }, {m:{}, l:[]}).l;
}


来源:https://stackoverflow.com/questions/32786654/finding-the-intersection-of-two-arrays-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!