I\'m having a integer array of 10 Million elements, how to write a function in C# which returns True if the array has a pair which sums up to 75.
My code is:
This will work if the array is sorted.
public bool ContainsPair(int[] array)
{
int i = 0;
int j = array.Length - 1;
while(i < j)
{
if (array[i] + array[j] == 75)
return true;
else if (array[i] + array[j] < 75)
i++;
else if (array[i] + array[j] > 75)
j--;
}
return false;
}
You use two pointers and walk towards the middle of the array. Pointer i starts at the beginning of the array, while j starts at the end. If you find two numbers that sum up to 75, you return true. If the sum is less than 75, then you move pointer i one step towards the middle and check again. If the sum is more than 75, you move pointer j one step towards the middle and check again.
If the two pointers meet, then you return false, because no pair was found.
This is O(n), not including sorting the array.