I have n numbers and a number z. I want to create an algorithm(pseudocode) to find if there are pairs (x,y) that x + y = z in O(nlogn).
I thought that i can run the quicksort algorithm. Then i will have 2 arrays: array1 (with elements < pivot) and array2 (with elements>pivot). if the first element in array is < z then i can check all the other elements in array1 to find pairs that x+y=z. else if the first element in array1 is >z then i go to array2 and make the same procedure. Is my suggestion true?
First, sort the array.
Then set one pointer/index to each end of the sorted array.
If they sum up to z
, you keep it and move both pointers towards the middle.
If the sum is smaller than z
, you move the pointer on the small end towards the middle.
If the sum is larger than z
, you move the pointer on the large end towards the middle.
When the pointers meet/pass, you're done.
The idea with the pivot is not going to work, because there is no good candidate for a pivot, and because checking unsorted half-range would remain an O(n) task that needs to be done n/2 times, for the overall complexity of O(n 2 ).
You can do it in O(n) without sorting by adding all elements to a hash table, and then checking for each element x
that zx
element also exists. A situation with x=z/2
is a special case, because you need to verify that two z/2
values exist in the input array.
You don't need be sorting an already sorted sequence, just searching it.
pseudocode:
sort(sequence) // O(NlogN) sorts are well known
for element in sequence: // O(N) loop
target = z - element // constant (assuming fixed size arithmetic)
if target > min_element and target < max_element: // constant
found = binary_search(target, sequence) // O(LogN) search
complexity: O(NlogN (sort) + (N (loop) * LogN (Search))) = O(NlogN), as required
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.