Given an array the size of n where: 1/2 of the array is with a single (unknown) value. 1/4 of the array is with a single (unknown) different value. And so on for 1/8, 1/16, 1/32 Give an algorithm to sort the array. You cannot use the find median algorithm
So what I figured is: There are only logn different values There is a simple solution using a binary heap on O ( n*loglogn) It looks like a question that needed to be solved in O (n)
Here is one possible approach:
The whole algorithm thus runs in amortized O(n) time, ie, it is dominated by eliminating duplicates and expanding the sorted array. The space complexity is O(n).
This is essentially optimal because you need to "touch" all the elements to print the sorted array, which means we have a matching lower bound of Omega(n) on the running time.
我们的想法是使用多数算法,该算法取O(n)然后发现什么是“半”值从数组中删除它然后再在新数组上再做n + n / 2 + n / 4 + n / 8 + ..... <2n => O(n)
Going over the array once, keep hash map for seen values. Like you said there are only log(n)
different values.
Now you have list of all the different values - sorting them will take lon(n)*log(log(n))
Once you have the sorted uniq like it's easy to constract the original array : The max value will take n/2
cells , the 2nd take n/4
and so on.
The Total run time is O(n + lon(n)*log(log(n)) + n)
which is O(n)
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.