Answer the question
In order to leave comments, you need to log in
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
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.
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 questionAsk a Question
731 491 924 answers to any question