Created
March 27, 2018 03:24
-
-
Save jianminchen/bae065b8b0ed18c9ae3850476f41d52b to your computer and use it in GitHub Desktop.
Find first missing number - using extra array to mark found
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; | |
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