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

前端 未结 14 1949
萌比男神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 11:58

    Use a hash table. Insert every number into your hash table, along with its index. Then, let S be your desired sum. For every number array[i] in your initial array, see if S - array[i] exists in your hash table with an index different than i.

    Average case is O(n), worst case is O(n^2), so use the binary search solution if you're afraid of the worst case.

提交回复
热议问题