R
R
Relocatik2019-07-15 16:29:27
Algorithms
Relocatik, 2019-07-15 16:29:27

How to develop an algorithm to find two elements whose sum gives x?

5d2c7f89c1387354247204.png
Please help me solve this problem, I can't think of anything

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Karpion, 2019-07-15
@Relocatik

First, order the set (array) S in ascending order.
Then we take two extreme elements, we consider their sum. Let's say the sum is more than necessary - then we discard the right (largest) element; and if less, then the leftmost one (well, we don’t discard it - but shift the pointer to the center of the array). And we repeat - until the desired amount is obtained or until the elements run out.

R
Ronald McDonald, 2019-07-15
@Zoominger

On freelance, they will "help".

R
Rsa97, 2019-07-15
@Rsa97

Fantastic way:
Learn O-notation.
Learn different algorithms with their complexity estimation in O-notation.
Select the necessary algorithms and carry out their composition in your own algorithm that solves the problem.
Real way:
Run through all the forums asking for help, maybe someone will respond.
PS The task, by the way, is primitive, in two steps, the first O(n log n), the second O(n).

P
pulk, 2019-07-27
@pulk

The condition says nothing about the use of additional memory, so it can be solved in O(N).
hashtable = {}
for x in X:
y = S - x
if y in hashtable:
return x, y
hashtable[x] = 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question