find pair of numbers in array that add to given sum

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

    Not guaranteed to be possible; how is the given sum selected?

    Example: unsorted array of integers

    2, 6, 4, 8, 12, 10
    

    Given sum:

    7
    

    ??

    0 讨论(0)
  • 2020-11-30 20:47

    Naïve double loop printout with O(n x n) performance can be improved to linear O(n) performance using O(n) memory for Hash Table as follows:

    void TwoIntegersSum(int[] given, int sum)
    {
        Hashtable ht = new Hashtable();
        for (int i = 0; i < given.Length; i++)
            if (ht.Contains(sum - given[i]))
                Console.WriteLine("{0} + {1}", given[i], sum - given[i]);
            else
                ht.Add(given[i], sum - given[i]);
        Console.Read();
    }
    
    0 讨论(0)
  • 2020-11-30 20:48

    First you should find reverse array => sum minus actual array then check whether any element from these new array exist in the actual array.

    const arr = [0, 1, 2, 6];
    
    const sum = 8;
    
    let isPairExist = arr
      .map(item => sum - item) // [8, 7, 6, 2];
      .find((item, index) => {
        arr.splice(0, 1); // an element should pair with another element
        return arr.find(x => x === item);
      })
      ? true : false;
    
    console.log(isPairExist);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 20:49

    First off, sort the array using radix sort. That'll set you back O(kN). Then proceed as @PengOne suggest.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题