C# fastest intersection of 2 sets of sorted numbers

前端 未结 5 1404
傲寒
傲寒 2020-12-28 10:00

I\'m calculating intersection of 2 sets of sorted numbers in a time-critical part of my application. This calculation is the biggest bottleneck of the whole application so I

5条回答
  •  礼貌的吻别
    2020-12-28 10:14

    Since both lists are sorted, you can arrive at the solution by iterating over them at most once (you may also get to skip part of one list, depending on the actual values they contain).

    This solution keeps a "pointer" to the part of list we have not yet examined, and compares the first not-examined number of each list between them. If one is smaller than the other, the pointer to the list it belongs to is incremented to point to the next number. If they are equal, the number is added to the intersection result and both pointers are incremented.

    var firstCount = firstSet.Count;
    var secondCount = secondSet.Count;
    int firstIndex = 0, secondIndex = 0;
    var intersection = new List();
    
    while (firstIndex < firstCount && secondIndex < secondCount)
    {
        var comp = firstSet[firstIndex].CompareTo(secondSet[secondIndex]);
        if (comp < 0) {
            ++firstIndex;
        }
        else if (comp > 0) {
            ++secondIndex;
        }
        else {
            intersection.Add(firstSet[firstIndex]);
            ++firstIndex;
            ++secondIndex;
        }
    }
    

    The above is a textbook C-style approach of solving this particular problem, and given the simplicity of the code I would be surprised to see a faster solution.

提交回复
热议问题