find pair of numbers in array that add to given sum

前端 未结 19 2164
萌比男神i
萌比男神i 2020-11-30 20:17

Question: Given an unsorted array of positive integers, is it possible to find a pair of integers from that array that sum up to a given sum?

Constraints: This shou

19条回答
  •  隐瞒了意图╮
    2020-11-30 20:50

    Here's an O(N) algorithm. It relies on an in-place O(N) duplicate removal algorithm, and the existence of a good hash function for the ints in your array.

    First, remove all duplicates from the array.

    Second, go through the array, and replace each number x with min(x, S-x) where S is the sum you want to reach.

    Third, find if there's any duplicates in the array: if 'x' is duplicated, then 'x' and 'S-x' must have occurred in the original array, and you've found your pair.

提交回复
热议问题