简体   繁体   中英

Array with specific values

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:

  • scan the array and store element frequencies (there are log n distinct elements) in a hash table in amortized O(n) time; this is doable because we can do insertions in amortized O(1) time ;
  • now run a classic sorting algorithm on these log n elements: this is doable in deterministic O(log n log log n) time using, say, heap sort or merge sort;
  • now expand the sorted array---or create a new one and fill it using the sorted array and the hash table---using frequencies from the hash table; this is doable in O(n) amortized time.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM