Reputation: 23
I have a problem with O(n * log(n)) searching algorithm.
I have to find two numbers from an array that add up to the given number.
I know how O(n * log(n)) works, but I'm not sure if those two correct numbers will meet in search if I do it like this:
for (int i = 0; i < n; i++)
for (int j = 1; j <= n; j = j*2)
Is there a way to keep O(n * log(n)) complexity so that every two numbers meet in the search?
Upvotes: 1
Views: 703
Reputation: 8163
sort array (O(nlogn))
for each element:
2.1 binary search to find other element that adds up to the given number (or to figure out there is none) (O(logn))
Step 2 has complexity O(nlogn), and so the whole algorithm has O(nlogn)
Upvotes: 1