Given a sorted array of integers, how can we find a pair of integers that sum to K?
e.g. array = 1,3,5,6,10, K = 6, the answer is 1 and 5.<
There is a linear (O(n)) solution.
Take a hashtable and while iterating through the array check if the current element is already in the hashtable - if so then you've found the answer. Otherwise insert the number which is equal to K minus the current element. Works for non sorted array, btw.
int[] ar = new int[] { 1, 4, 3, 5 };
int K = 6;
HashSet set = new HashSet();
foreach (int a in ar)
{
if (set.Contains(a))
{
Console.WriteLine(a + ", " + (K - a));
break;
}
set.Add(K - a);
}