find pair of numbers in array that add to given sum

前端 未结 19 2221
萌比男神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:49

    AS @PengOne mentioned it's not possible in general scheme of things. But if you make some restrictions on i/p data.

    1. all elements are all + or all -, if not then would need to know range (high, low) and made changes.
    2. K, sum of two integers is sparse compared to elements in general.
    3. It's okay to destroy i/p array A[N].

    Step 1: Move all elements less than SUM to the beginning of array, say in N Passes we have divided array into [0,K] & [K, N-1] such that [0,K] contains elements <= SUM.

    Step 2: Since we know bounds (0 to SUM) we can use radix sort.

    Step 3: Use binary search on A[K], one good thing is that if we need to find complementary element we need only look half of array A[K]. so in A[k] we iterate over A[ 0 to K/2 + 1] we need to do binary search in A[i to K].

    So total appx. time is, N + K + K/2 lg (K) where K is number of elements btw 0 to Sum in i/p A[N]

    Note: if you use @PengOne's approach you can do step3 in K. So total time would be N+2K which is definitely O(N)

    We do not use any additional memory but destroy the i/p array which is also not bad since it didn't had any ordering to begin with.

提交回复
热议问题