V
V
Victor2015-07-10 19:44:01
Algorithms
Victor, 2015-07-10 19:44:01

Given an array S of n real numbers and a number x. How to determine in O(nlogn) time whether x can be represented as the sum of two elements from S?

Is it possible to come up with an algorithm in O (nlogn) time, I could only come up with a search for sums of two elements.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mrrl, 2015-07-10
@AkylaQD

1) sort the array
2) start up two pointers - one from the beginning, the other from the end. If the sum of the elements below them is less than X - increase the first one, if more - decrease the second one. If equal - you won, take the prize from the shelf.
3) if the pointers met, and the sum never equaled X, then you lost, you can shoot.

V
Vitaly Vitrenko, 2015-07-10
@Vestail

We sort the array and then from i = 0 to N we look for the number xS[i] in the array using binary search. If found, we exit the cycle and report a positive result.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question