Fast intersection of two sorted integer arrays

后端 未结 5 654
说谎
说谎 2021-02-04 11:02

I need to find the intersection of two sorted integer arrays and do it very fast.

Right now, I am using the following code:

int i = 0, j = 0;

while (i          


        
5条回答
  •  Happy的楠姐
    2021-02-04 11:41

    Have you tried something simple like this:

    var a = Enumerable.Range(1, int.MaxValue/100).ToList();
    var b = Enumerable.Range(50, int.MaxValue/100 - 50).ToList();
    
    //var c = a.Intersect(b).ToList();
    List c = new List();
    
    var t1 = DateTime.Now;
    
    foreach (var item in a)
    {
        if (b.BinarySearch(item) >= 0)
            c.Add(item);
    }
    
    var t2 = DateTime.Now;
    
    var tres = t2 - t1;
    

    This piece of code takes 1 array of 21,474,836 elements and the other one with 21,474,786

    If I use var c = a.Intersect(b).ToList(); I get an OutOfMemoryException

    The result product would be 461,167,507,485,096 iterations using nested foreach

    But with this simple code, the intersection occurred in TotalSeconds = 7.3960529 (using one core)

    Now I am still not happy, so I am trying to increase the performance by breaking this in parallel, as soon as I finish I will post it

提交回复
热议问题