Skip to content

Instantly share code, notes, and snippets.

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/23ecd823793505113b46be92c5a582fe to your computer and use it in GitHub Desktop.
Save jianminchen/23ecd823793505113b46be92c5a582fe to your computer and use it in GitHub Desktop.
Get a different number - being interviewer -
using System;
using System.Collections.Generic;
/// [0, 3, 2, 1]
/// [0, 2, 1, ]
/// iterate starting from 0 --> inc 1 -->
class Solution
{
public static int GetDifferentNumber(int[] arr)
{
var set = new HashSet<int>();
foreach(var element in arr){
set.Add(element);
}
for(int i = 0; i < arr.Length + 1; i++) {
if(!set.Contains(i)) {
return i;
}
}
// should not reach here ever.
return -1;
}
/// can modify the array
public static int GetDifferentNumber2(int[] arr)
{
for(int i = 0; i < arr.Length; i++) {
var current = arr[i];
if(current < arr.Length && current != i){
int temp = arr[current];
arr[current] = current;
arr[i] = temp;
}
}
for(int i = 0; i < arr.Length; i++) {
if(i != arr[i]){
return i;
}
}
return arr.Length;
}
static void Main(string[] args)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment