Tuesday, March 29, 2011

find Missing int - amazon question

static private void findMissing(int[] intArray, int n)
{
bool[] bitArray = new bool[n];

if (intArray == null)
throw new Exception("findMissing - intArray is null");

for (int i = 0; i < n; i++)
bitArray[i] = false;

foreach (int x in intArray)
{
if (x < 0 || x >= n)
throw new Exception("findMissing - x is out of range - x=" + x);
bitArray[x] = true;
}
for (int i = 0; i < n; i++)
{
//Console.WriteLine("i=" + i + " bit=" + bitArray[i].ToString());
if (!bitArray[i])
Console.WriteLine("Missing element at i=" + i);
}
}

static private void testFindMissing()
{
int[] intArray = new int[]{ 1, 2, 4, 7, 3, 5, 6, 0, 9, 10 };
findMissing(intArray, 11);
Console.ReadLine();
}

No comments:

Post a Comment