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

前端 未结 14 1953
萌比男神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:09

    I'm sure there's a better way, but here's an idea:

    1. Sort array
    2. For every element e in the array, binary search for the complement (sum - e)

    Both these operations are O(n log n).

提交回复
热议问题