find pair of numbers in array that add to given sum

前端 未结 19 2187
萌比男神i
萌比男神i 2020-11-30 20:17

Question: Given an unsorted array of positive integers, is it possible to find a pair of integers from that array that sum up to a given sum?

Constraints: This shou

19条回答
  •  悲哀的现实
    2020-11-30 20:47

    Naïve double loop printout with O(n x n) performance can be improved to linear O(n) performance using O(n) memory for Hash Table as follows:

    void TwoIntegersSum(int[] given, int sum)
    {
        Hashtable ht = new Hashtable();
        for (int i = 0; i < given.Length; i++)
            if (ht.Contains(sum - given[i]))
                Console.WriteLine("{0} + {1}", given[i], sum - given[i]);
            else
                ht.Add(given[i], sum - given[i]);
        Console.Read();
    }
    

提交回复
热议问题