two sorted array A, B
with length n,m
(n <= m)
, and k
which (k >= log n)
is given.
with log (nm)
we can find k-th
smallest number in union of these two array.
I have a solution In problem 2 here , but my challenge is why two given condition "(n <= m)" and "k >= log n" does not affect this algorithm?
First assumption: n <= m
is an assumption "without loss of generality". If n >= m, then just swap A and B in your head. They included this assumption even though it was not needed, because they felt it was "free" to make this assumption.
Second assumption: A trivial algorithm to find the k
th smallest element is to iterate over A and B simultaneously, advancing in the array that has the smaller element of the two. This would be exactly like running the "Merge" function from mergesort, but stopping once you've merged the first k elements. The complexity would be O(k). They wanted you to find a more complex algorithm, so they "ruled out" this algorithm by stating that k >= log(n), which implies that complexity O(k) is never better than O(log(n)). Technically, if they wanted to thoroughly rule this algorithm out, they should also have stated that k <= n + m - log(n)
, otherwise you could run the "merge" function from the end: merge the n+mk largest elements, then return the n+mk
th largest element, which is the same as the kth smallest element.
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.