查找最小的破坏连续性的数字
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); }
c++
int search(int ar[], int size) { int a = 0, b = size - 1; int mid; 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; } return (ar[a] + 1); }
#include <boost/range/counting_range.hpp> #include <boost/range/irange.hpp> #include <boost/iterator/counting_iterator.hpp> auto i = mismatch(l.begin(), l.end(), boost::counting_range(1100, 1111).begin());
if (i.first == l.end()) {
}
else
std::cout << "the first missing number is " << *i.second << '\n';
参考:
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/