Created
September 30, 2018 11:20
-
-
Save aloisdg/38ff759ea593b8d3a3d68459690dc062 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.Linq; | |
public class Program | |
{ | |
public static bool Contains(int[] ints, int k) | |
{ | |
if (ints.Length == 0) | |
return false; | |
if (ints.Length == 1) | |
return k == ints[0]; | |
var position = ints.Length / 2; | |
var middle = ints[position]; | |
if (k == middle) | |
return true; | |
// for perf we might want to use resize, copy or ArraySegment | |
var scope = k > middle ? ints.Skip(position) : ints.Take(position); | |
return Contains(scope.ToArray(), k); | |
} | |
public static bool Exists(int[] ints, int k) | |
{ | |
return Contains(ints, k); | |
} | |
public static void Main() | |
{ | |
Console.WriteLine(Exists(new int[]{},1) == false); | |
Console.WriteLine(Exists(new int[]{0},1) == false); | |
Console.WriteLine(Exists(new int[]{1},1) == true); | |
Console.WriteLine(Exists(new int[]{0,1},1) == true); | |
Console.WriteLine(Exists(new int[]{0,1},0) == true); | |
Console.WriteLine(Exists(new int[]{0,2},1) == false); | |
Console.WriteLine(Exists(new int[]{0,1,2},1) == true); | |
Console.WriteLine(Exists(new int[]{0,1,2},2) == true); | |
Console.WriteLine(Exists(new int[]{0,1,2,4},2) == true); | |
Console.WriteLine(Exists(new int[]{0,1,2,3,4},4) == true); | |
Console.WriteLine(Exists(new int[]{0,1,2,3,102},102) == true); | |
Console.WriteLine(Exists(new int[]{0,1,2,3,102,102,102,102,102},102) == true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://dotnetfiddle.net/N1nUCr