checking if 2 numbers of array add up to I

后端 未结 15 2647
日久生厌
日久生厌 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 01:54

    If you have the range which the integers are within, you can use a counting sort-like solution where you scan over the array and count an array up. Ex you have the integers

    input = [0,1,5,2,6,4,2]
    

    And you create an array like this:

    count = int[7]
    

    which (in Java,C# etc.) are suited for counting integers between 0 and 6.

    foreach integer in input
        count[i] = count[i] + 1
    

    This will give you the array [1,1,2,0,1,1,1]. Now you can scan over this array (half of it) and check whether there are integers which adds up to i like

    for j = 0 to count.length - 1
        if count[j] != 0 and count[i - j] != 0 then // Check for array out-of-bounds here
             WUHUU! the integers j and i - j adds up
    

    Overall this algorithm gives you O(n + k) where n is from the scan over the input of length n and k is the scan over the count array of length k (integers between 0 and k - 1). This means that if n > k then you have a guaranteed O(n) solution.

提交回复
热议问题