查找最小的破坏连续性的数字

c#

public static class MyExtensions

{
 
    /// <summary>
 
    /// Finds the missing numbers in a list.
 
    /// </summary>
 
    /// <param name="list">List of numbers</param>
 
    /// <returns>Missing numbers</returns>
 
    public static IEnumerable<int> FindMissing(this List<int> list)
 
    {
 
        // Sorting the list
 
        list.Sort();



        // First number of the list
 
        var firstNumber = list.First();

// Last number of the list
 
        var lastNumber = list.Last();



        // Range that contains all numbers in the interval
     // [ firstNumber, lastNumber ]
        var range = Enumerable.Range(firstNumber, lastNumber - firstNumber);



        // Getting the set difference
 
        var missingNumbers = range.Except(list);



        return missingNumbers;
 
    }
}
}

java

从1开始 

public static int findFirstMissing(int ar[],
                      int size)
    {
        int a = 0, b = size - 1;
        int mid = 0;
        while ((b - a) > 1)
        {
            mid = (a + b) / 2;
            if ((ar[a] - a) != (ar[mid] - mid))
                b = mid;
            else if ((ar[b] - b) != (ar[mid] - mid))
                a = mid;
            else
                return ar[size-1]+1;
        }
        mid = a + (b -a)/2;
        return (ar[mid] + 1);
    }

参考:

https://www.leniel.net/2009/10/finding-missing-numbers-in-list-csharp.html

https://www.geeksforgeeks.org/find-the-missing-number-in-a-sorted-array/

猜你喜欢

转载自www.cnblogs.com/wolbo/p/11428722.html