Find two elements in an array that sum to k [dupli

2020-01-28 08:16发布

Possible Duplicate:
Given two arrays a and b .Find all pairs of elements (a1,b1) such that a1 belongs to Array A and b1 belongs to Array B whose sum a1+b1 = k .

Given : An unsorted array A of integers
Input : An integer k

Output : All the two element set with sum of elements in each set equal to k in O(n).

Example:

A = {3,4,5,1,4,2}

Input : 6
Output : {3,3}, {5,1}, {4,2}

Note : I know an O(n logn) solution but that would require to have the array sorted. Is there any way by which this problem can be solved in O(n). An non-trivial C++ data structure can be used i.e there's no bound on space

5条回答
Luminary・发光体
2楼-- · 2020-01-28 08:32

There are k pairs of integers that sum to k: {0,k}, {1,k-1}, ... etc. Create an array B of size k+1 where elements are boolean. For each element e of the array A, if e <= k && B[e] == false, set B[e] = true and if B[k-e] == true, emit the pair {e,k-e}. Needs to be extended slightly for negative integers.

查看更多
我只想做你的唯一
3楼-- · 2020-01-28 08:33

Make a constant-time lookup table (hash) so you can see if a particular integer is included in your array (O(n)). Then, for each element in the array, see if k-A[i] is included. This takes constant time for each element, so a total of O(n) time. This assumes the elements are distinct; it is not difficult to make it work with repeating elements.

查看更多
▲ chillily
4楼-- · 2020-01-28 08:35

http://codepad.org/QR9ptUwR

This will print all pairs. The algorithm is same as told by @bdares above.

I have used stl maps as we dont have hash tables in STL.

查看更多
男人必须洒脱
5楼-- · 2020-01-28 08:39

One can reduce the,

Element Uniqueness bit,

to this. No O(n).

查看更多
甜甜的少女心
6楼-- · 2020-01-28 08:57

Just a simple algorithm off the top of my head:

  • Create a bitfield that represents the numbers from 0 to k, labeled B
  • For each number i in A
    • Set B[i]
    • If B[k-i] is set, add (i, k-i) to the output

Now as people have raised, if you need to have two instances of the number 3 to output (3, 3) then you just switch the order of the last two statements in the above algorithm.

Also I'm sure that there's a name for this algorithm, or at least some better one, so if anyone knows I'd be appreciative of a comment.

查看更多
登录 后发表回答