Find a pair of elements from an array whose sum equals a given number

后端 未结 30 1369
暗喜
暗喜 2020-11-22 10:14

Given array of n integers and given a number X, find all the unique pairs of elements (a,b), whose summation is equal to X.

The following is my solution, it is O(nLo

30条回答
  •  悲&欢浪女
    2020-11-22 10:52

    There are 3 approaches to this solution:

    Let the sum be T and n be the size of array

    Approach 1:
    The naive way to do this would be to check all combinations (n choose 2). This exhaustive search is O(n2).

    Approach 2: 
     A better way would be to sort the array. This takes O(n log n)
    Then for each x in array A, use binary search to look for T-x. This will take O(nlogn).
    So, overall search is  O(n log n)

    Approach 3 :
    The best way would be to insert every element into a hash table (without sorting). This takes O(n) as constant time insertion.
    Then for every x, we can just look up its complement, T-x, which is O(1).
    Overall the run time of this approach is O(n).


    You can refer more here.Thanks.


提交回复
热议问题