checking if 2 numbers of array add up to I

后端 未结 15 2690
日久生厌
日久生厌 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

    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

提交回复
热议问题