Find all pairs of integers within an array which sum to a specified value

前端 未结 15 2021
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 08:00

Design an algorithm to find all pairs of integers within an array which sum to a specified value.

I have tried this problem using a hash

15条回答
  •  清歌不尽
    2020-12-01 08:24

    1. If the array is sorted:

      Let i = 0, j = end of array, sum = the value you are looking for, then do:

      If i+j = sum, then output (i,j).
      If i+j < sum, then move i to the right one position.
      If i+j > sum, then move j to the left one position.

      Time complexity: O(n). Space complexity: O(1).

    2. If the array is not sorted, there are a few ways to approach this problem:

      1. Sort the array and then use the above approach.

      2. HashMap:

        Store all elements in a HashMap.

        a+b=sum, so b=sum-a. For each element a of the array, look up b from the HashMap.

        HashMap lookup takes amortized O(1).

        Time complexity: O(n). Space complexity: O(n).

      3. BitMap:

        Iterate through the input to create a bitmap where each bit corresponds to an element value. Say the input is {2,5,8}, then we toggle the bitmap array's indices 2, 5 and 8 from binary 0 to 1. This takes O(1) per element, thus O(n) in total.

        Go through the input again. We know b=sum-a, so for every element a in the input, look up its b, which can be done in O(1) since it's a bitmap index. This also takes O(n) in total.

        Time complexity: O(n) + O(n) = O(n). Space complexity: bitmap space = O(n).

提交回复
热议问题