Check for missing number in sequence

前端 未结 14 1574
太阳男子
太阳男子 2020-12-04 17:58

I have an List which contains 1,2,4,7,9 for example.

I have a range from 0 to 10.

Is there a way to determine what numbers are missin

14条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 18:14

    An alternative method which works in general for any two IEnunumerable where T :IComparable. If the IEnumerables are both sorted, this works in O(1) memory (i.e. there is no creating another ICollection and subtracting, etc.) and in O(n) time.

    The use of IEnumerable and GetEnumerator makes this a little less readable, but far more general.

    Implementation

    /// 
    /// For two sorted IEnumerable<T> (superset and subset),
    /// returns the values in superset which are not in subset.
    /// 
    public static IEnumerable CompareSortedEnumerables(IEnumerable superset, IEnumerable subset)
        where T : IComparable
    {
        IEnumerator supersetEnumerator = superset.GetEnumerator();
        IEnumerator subsetEnumerator = subset.GetEnumerator();
        bool itemsRemainingInSubset = subsetEnumerator.MoveNext();
    
        // handle the case when the first item in subset is less than the first item in superset
        T firstInSuperset = superset.First();
        while ( itemsRemainingInSubset && supersetEnumerator.Current.CompareTo(subsetEnumerator.Current) >= 0 )
            itemsRemainingInSubset = subsetEnumerator.MoveNext();
    
        while ( supersetEnumerator.MoveNext() )
        {
            int comparison = supersetEnumerator.Current.CompareTo(subsetEnumerator.Current);
            if ( !itemsRemainingInSubset || comparison < 0 )
            {
                yield return supersetEnumerator.Current;
            }
            else if ( comparison >= 0 )
            {
                while ( itemsRemainingInSubset && supersetEnumerator.Current.CompareTo(subsetEnumerator.Current) >= 0 )
                    itemsRemainingInSubset = subsetEnumerator.MoveNext();
            }
        }
    }
    

    Usage

    var values = Enumerable.Range(0, 11);
    var list = new List { 1, 2, 4, 7, 9 };
    var notIncluded = CompareSortedEnumerables(values, list);
    

提交回复
热议问题