[removed] efficiently compare two integer arrays

后端 未结 6 1295
庸人自扰
庸人自扰 2020-12-30 03:14

I have two integer arrays which contain numeric values. I want to look through both lists and check for commonality (or lack of) between the lists. I.e. I want to iterate th

6条回答
  •  梦毁少年i
    2020-12-30 04:08

    Sort both arrays, than loop just once and compare:

    function diff(arrayToCompareTo, comparedArray)
    {
      Sort(arrayToCompareTo);
      Sort(comparedArray);
    
      var difference = [], same = [];
      for(var i = 0; i < arrayToCompareTo.length; ++i)
      {
         if (arrayToCompareTo[i] != comparedArray[i])
            difference.push(comparedArray[i]);
         else
            same.push(comparedArray[i]);
      }
    
      if (comparedArray.length > arrayToCompareTo.length)
         for(var i = arrayToCompareTo.length; i < comparedArray.length; ++i)
           difference.push(comparedArray[i]);
    }
    

    This is not tested so if something is wrong please let me know.
    Anyway this should set you to the right direction since it's O(N) at best and O(M) at worst if comparedArray.length > arrayToCompareTo.length, it's much more efficient than O(N^2). Note that the sorting takes O(N log N).

提交回复
热议问题