Check for missing number in sequence

前端 未结 14 1539
太阳男子
太阳男子 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:26

    This method does not use LINQ and works in general for any two IEnunumerable<T> where T :IComparable

    public static IEnumerable<T> FindMissing<T>(IEnumerable<T> superset, IEnumerable<T> subset) where T : IComparable
    {
        bool include = true;
        foreach (var i in superset)
        {
            foreach (var j in subset)
            {
                include = i.CompareTo(j) == 0;
                if (include)
                    break;
            }
            if (!include)
                yield return i;
        }
    }
    
    0 讨论(0)
  • 2020-12-04 18:27

    for a List L a general solution (works in all programming languages) would be simply

    L.Count()*(L.Count()+1)/2 - L.Sum();

    which returns the expected sum of series minus the actual series.

    for a List of size n the missing number is:

    n(n+1)/2 - (sum of list numbers)

    0 讨论(0)
提交回复
热议问题