find pair of numbers in array that add to given su

2020-01-27 10:06发布

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 should be done in O(n) and in-place (without any external storage like arrays, hash-maps) (you can use extra variables/pointers)

If this is not possible, can there be a proof given for the same?

19条回答
Bombasti
2楼-- · 2020-01-27 10:51

The following site gives a simple solution using hashset that sees a number and then searches the hashset for given sum-current number http://www.dsalgo.com/UnsortedTwoSumToK.php

查看更多
时光不老,我们不散
3楼-- · 2020-01-27 10:55

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);
查看更多
三岁会撩人
4楼-- · 2020-01-27 11:01

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

??

查看更多
倾城 Initia
5楼-- · 2020-01-27 11:01
def pair_sum(arr,k):
    counter = 0
    lookup = set()
    for num in arr:
        if k-num in lookup:
            counter+=1
        else:
            lookup.add(num)
    return counter
    pass
pair_sum([1,3,2,2],4)

The solution in python

查看更多
放我归山
6楼-- · 2020-01-27 11:02

This might be possible if the array contains numbers, the upper limit of which is known to you beforehand. Then use counting sort or radix sort(o(n)) and use the algorithm which @PengOne suggested.

Otherwise I can't think of O(n) solution.But O(nlgn) solution works in this way:-

First sort the array using merge sort or quick sort(for inplace). Find if sum - array_element is there in this sorted array. One can use binary search for that.

So total time complexity: O(nlgn) + O(lgn) -> O(nlgn).
查看更多
戒情不戒烟
7楼-- · 2020-01-27 11:02

Ruby implementation

ar1 = [ 32, 44, 68, 54, 65, 43, 68, 46, 68, 56]
for i in 0..ar1.length-1
 t  = 100 - ar1[i]
  if ar1.include?(t)
    s= ar1.count(t)
    if s < 2
      print   s , " - " ,  t, " , " , ar1[i]  , " pair ", i, "\n"
    end
  end
end
查看更多
登录 后发表回答