Find if pair of elements with given sum exists in large integer array

前端 未结 5 2077
独厮守ぢ
独厮守ぢ 2021-01-15 07:45

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:

5条回答
  •  爱一瞬间的悲伤
    2021-01-15 08:41

    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.

提交回复
热议问题