简体   繁体   English

两个排序数组并找到第 k 个最小的数字

[英]two sorted array and find k'th smallest number

two sorted array A, B with length n,m (n <= m) , and k which (k >= log n) is given.两个排序数组A, B ,长度为n,m (n <= m)k ,其中(k >= log n)已给出。

with log (nm) we can find k-th smallest number in union of these two array.使用log (nm)我们可以在这两个数组的联合中找到k-th最小的数字。

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?我在这里的问题 2 中有一个解决方案,但我的挑战是为什么两个给定条件“(n <= m)”和“k >= log n”不影响该算法?

  • First assumption: n <= m is an assumption "without loss of generality".第一个假设: n <= m是一个“不失一般性”的假设。 If n >= m, then just swap A and B in your head.如果 n >= m,那么只需在头脑中交换 A 和 B。 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.第二个假设:找到第k个最小元素的简单算法是同时迭代 A 和 B,在具有两者中较小元素的数组中前进。 This would be exactly like running the "Merge" function from mergesort, but stopping once you've merged the first k elements.这与从 mergesort 运行“Merge”function 完全一样,但是在合并前 k 个元素后停止。 The complexity would be O(k).复杂度为 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)).他们希望你找到一个更复杂的算法,所以他们通过声明 k >= log(n) 来“排除”这个算法,这意味着复杂度 O(k) 永远不会比 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.从技术上讲,如果他们想彻底排除这个算法,他们还应该声明k <= n + m - log(n) ,否则你可以从最后运行“合并” function :合并 n+mk 个最大元素,然后返回第n+mk个最大的元素,与第k小的元素相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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