Skip to content

Instantly share code, notes, and snippets.

@WennderSantos
Created November 23, 2018 17:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WennderSantos/d9a8bd845b9cee761093cdbf72ed8738 to your computer and use it in GitHub Desktop.
Save WennderSantos/d9a8bd845b9cee761093cdbf72ed8738 to your computer and use it in GitHub Desktop.
Find pairs that sum to eight. O(n)
static void Main(string[] args)
{
var input = new int[]{4, 5, 2, 3, 4, 1};
var memory = new Dictionary<int, int>();
var results = new List<(int idx1, int idx2)>();
for (var i = 0; i < input.Length; i++)
{
if (memory.ContainsKey(input[i]))
results.Add((memory[input[i]], i));
else
memory.Add(8 - input[i], i);
}
foreach(var (idx1, idx2) in results)
Console.WriteLine($"Sum of {input[idx1]} and {input[idx2]} is 8");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment