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

前端 未结 15 2011
隐瞒了意图╮
隐瞒了意图╮ 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:32

    If you don't mind spending O(M) in space, where M is the sum you are seeking, you can do this in O(N + M) time. Set sums[i] = 1 when i <= M on a single pass over N, then check (sums[i] && sums[M-i]) on a single pass over M/2.

提交回复
热议问题