Last active
August 29, 2015 14:24
-
-
Save aivascu/388bd7a2fdf1e02543f6 to your computer and use it in GitHub Desktop.
Get first missing number in an array. (LINQ independent)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
public class Program | |
{ | |
public static int GetFirstMissingNumber(int[] positions) | |
{ | |
int maxPositions; | |
var posMax = 0; | |
var posCount = 0; | |
foreach(int pos in positions){ | |
if(posMax < pos) | |
posMax = pos; | |
posCount++; | |
} | |
if (posCount != 0) | |
{ | |
maxPositions = posMax > 0 && posMax > posCount ? posMax : posCount; | |
} | |
else | |
{ | |
maxPositions = 1; | |
} | |
byte[] posOrder = new byte[maxPositions]; | |
foreach (int pos in positions) | |
{ | |
if (pos > 0) | |
posOrder[pos - 1] = 1; | |
} | |
for (var i = 0; i < maxPositions; i++) | |
{ | |
if (posOrder[i] == 0) | |
return i + 1; | |
} | |
return maxPositions + 1; | |
} | |
public static void Main() | |
{ | |
List<int[]> testList = new List<int[]>{ | |
new int[4] {5, 1, 3, 4}, | |
new int[4] {0, 0, 0, 4}, | |
new int[4] {0, 4, 3, 2}, | |
new int[4] {1, 0, 3, 2} | |
}; | |
foreach(var arr in testList) | |
{ | |
Console.WriteLine("Missing Number {0}", GetFirstMissingNumber(arr)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment