checking if 2 numbers of array add up to I

后端 未结 15 2662
日久生厌
日久生厌 2020-12-15 01:13

I saw a interview question as follows: Give an unsorted array of integers A and and an integer I, find out if any two members of A add up to I.

any clues?

ti

15条回答
  •  误落风尘
    2020-12-15 02:01

    1. sort the array
    2. for each element X in A, perform a binary search for I-X. If I-X is in A, we have a solution.

    This is O(nlogn).

    If A contains integers in a given (small enough) range, we can use a trick to make it O(n):

    1. we have an array V. For each element X in A, we increment V[X].
    2. when we increment V[X] we also check if V[I-X] is >0. If it is, we have a solution.

提交回复
热议问题