Skip to content

Instantly share code, notes, and snippets.

@WennderSantos
Created February 20, 2019 00:06
Show Gist options
  • Save WennderSantos/3ac75a5b03f9f4dfb7a6ded46a6a7b83 to your computer and use it in GitHub Desktop.
Save WennderSantos/3ac75a5b03f9f4dfb7a6ded46a6a7b83 to your computer and use it in GitHub Desktop.
Find the smallest number present in two arrays
class Program
{
static void Main(string[] args)
{
var arr1 = new int[] { 10, 12, 5, 6, 3 };
var arr2 = new int[] { 1, 9, 4, 8, 2, 3 };
var arr1Sort = new int[] { 5, 8, 9, 13 };
var arr2Sort = new int[] { 6, 7, 10, 11, 12, 13 };
Console.WriteLine(FindSmallestNotSorted(arr1, arr2));
Console.WriteLine(FindSmallestSorted(arr1Sort, arr2Sort));
}
static int FindSmallestNotSorted(int[] arr1, int[] arr2)
{
//O(n^2)
//var result = -1;
//for(var i = 0; i< arr1.Length; i++)
//{
// for (var j = 0; j < arr2.Length; j++)
// {
// if(arr1[i] == arr2[j])
// {
// if (result == -1 || result > arr1[i])
// {
// result = arr1[i];
// break;
// }
// }
// }
//}
//return result;
//O(n log n)
Array.Sort(arr1);
Array.Sort(arr2);
return FindSmallestSorted(arr1, arr2);
}
//O(n)
static int FindSmallestSorted(int[] arr1, int[] arr2)
{
var idx1 = 0;
var idx2 = 0;
while(idx1 < arr1.Length && idx2 < arr2.Length)
{
if (arr1[idx1] > arr2[idx2])
{
idx2++;
continue;
}
if (arr1[idx1] < arr2[idx2])
{
idx1++;
continue;
}
return arr1[idx1];
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment