[removed] efficiently compare two integer arrays

后端 未结 6 1270
庸人自扰
庸人自扰 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条回答
  •  礼貌的吻别
    2020-12-30 03:42

    I think I have solution with efficiency of O(N) (no sort needed), here it is:

    var firstNotSecond;
    function CompareIntArrays(arr1, arr2)
    {
        firstNotSecond = new Array();
    
        var arr3 = new Array(); //appear in both
        var arrTemp = new Array(); //used for firstNotSecond
        var usedNumbers = new Array();
    
        for (var i = 0; i < arr1.length; i++)
        {
            var key = arr1[i];
            usedNumbers[key] = true;
            arrTemp[key + ""] = true;
        }
    
        for (var i = 0; i < arr2.length; i++)
        {
            var key = arr2[i];
            if (usedNumbers[key])
            {
                arr3[arr3.length] = key;
                arrTemp[key] = false;
            }
        }
    
        for (var key in arrTemp)
            if (arrTemp[key])
                firstNotSecond[firstNotSecond.length] = parseInt(key);
    
        return arr3;
    }
    

    The function will return new array with the items that exist in both arrays, and will assign global array with all items existing in first array that do not exist in second array.

    This code is relying on the fact both arrays hold only integer numbers.

    Usage example:

    alert(CompareIntArrays([15, 551, 25, 910, 11], [25, 11, 785, 880, 15]));
    alert(firstNotSecond);
    

    Tested with arrays having 100,000 items: less than one second. Tested with arrays having 200,000 items each: less than 2 seconds.

提交回复
热议问题