How to write an algorithm to check if the sum of any two numbers in an array/list matches a given number?

前端 未结 14 1973
萌比男神i
萌比男神i 2021-01-30 11:29

How can I write an algorithm to check if the sum of any two numbers in an array/list matches a given number with a complexity of nlogn?

14条回答
  •  长情又很酷
    2021-01-30 12:14

    This can be done in O(n) using a hash table. Initialize the table with all numbers in the array, with number as the key, and frequency as the value. Walk through each number in the array, and see if (sum - number) exists in the table. If it does, you have a match. After you've iterated through all numbers in the array, you should have a list of all pairs that sum up to the desired number.

    array = initial array
    table = hash(array)
    S = sum
    
    for each n in array
        if table[S-n] exists
            print "found numbers" n, S-n
    

    The case where n and table[S-n] refer to the same number twice can be dealt with an extra check, but the complexity remains O(n).

提交回复
热议问题