Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created March 27, 2018 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/bae065b8b0ed18c9ae3850476f41d52b to your computer and use it in GitHub Desktop.
Save jianminchen/bae065b8b0ed18c9ae3850476f41d52b to your computer and use it in GitHub Desktop.
Find first missing number - using extra array to mark found
using System;
class Solution
{
public static int GetDifferentNumber(int[] arr)
{
if(arr == null)
return 0;
var length = arr.Length;
var found = new int[length];
for(int i = 0; i < length; i++)
{
var current = arr[i]; // 10
var isInRange = current < length; // false
if(isInRange)
{
found[current] = 1;
}
}
// Try to find first element with value 0
for(int i = 0; i < length; i++)
{
if(found[i] == 0) // found[0] = 0
{
return i;
}
}
return length;
}
static void Main(string[] args)
{
}
}
/*
keywords:
unique, nonnegative, integer, an array
Ask: find smallest nonnegative integer not in the array
Constraint: not allow to modify the input arr.
[0, 1, 2, 3] -> 4
Array size is 4, 0 - 3, then missing is 4. answer is <= 3
declare an extra array, [1, 1, 1, 1] -> missing is SIZE = , 0 -> size - 1
[4, 3, 2, 1, 0]
Extra array:
[1,1,1,1,1] -> 5
iterate original array, update extra array
scan the extra array from left to right, find first element with value 0.
Time complexity: O(n), n is size of the array
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment