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

前端 未结 14 1975
萌比男神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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 11:56

    Let us say that we want to find two numbers in the array A that when added together equal N.

    1. Sort the array.
    2. Find the largest number in the array that is less than N/2. Set the index of that number as lower.
    3. Initialize upper to be lower + 1.
    4. Set sum = A[lower] + A[upper].
    5. If sum == N, done.
    6. If sum < N, increment upper.
    7. If sum > N, decrement lower.
    8. If either lower or upper is outside the array, done without any matches.
    9. Go back to 4.

    The sort can be done in O(n log n). The search is done in linear time.

提交回复
热议问题