checking if 2 numbers of array add up to I

后端 未结 15 2613
日久生厌
日久生厌 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.
    0 讨论(0)
  • 2020-12-15 02:01

    For example, loop and add possible number to set or hash and if found, just return it.

    >>> A = [11,3,2,9,12,15]
    >>> I = 14
    >>> S = set()
    >>> for x in A:
    ...     if x in S:
    ...         print I-x, x
    ...     S.add(I-x)
    ...
    11 3
    2 12
    >>>
    
    0 讨论(0)
  • 2020-12-15 02:01
    O(n) time and O(1) space
    

    If the array is sorted there is a solution in O(n) time complexity.

    Suppose are array is array = {0, 1, 3, 5, 8, 10, 14}

    And our x1 + x2 = k = 13, so output should be= 5, 8

    1. Take two pointers one at start of array, one at end of array
    2. Add both the elements at ptr1 and ptr2 array[ptr1] + array[ptr2]
    3. if sum > k then decrement ptr2 else increment ptr1
    4. Repeat step2 and step3 till ptr1 != ptr2

    Same thing explained in detail here. Seems like an Amazon interview Question http://inder-gnu.blogspot.com/2007/10/find-two-nos-in-array-whose-sum-x.html

    0 讨论(0)
提交回复
热议问题