多尔衮对小T 说:# pets - 心有所宠
c*g
1 楼
Question: Find the k-th Smallest Element in the Union of Two Sorted Arrays
Given two sorted arrays A, B of size m and n respectively. Find the k-th
smallest element in the union of A and B. You can assume that there are no
duplicate elements.
http://www.leetcode.com/2011/01/find-k-th-smallest-element-in-u
如果A组划k/2,B组划k/2来比较。为方便解释,这里先假设k为偶数,并且m,n>k/2.
如果不满足这些条件,在计算index的时候,会考虑这些情况。
if A[k/2 - 1] == B[k/2 -1] done.
if A[k/2 - 1] > B[k/2 -1]
那么在A[k/2 + 1 - k] 和 B[0 k/2 - 1] 里取k/2 smallest number。
if A[k/2 - 1] < B[k/2 -1] in a similar way
所以是一个recursion问题。而且数组大小按照对半的速度下降。所以是O(lgk)
另外,如果k很大,超过(m+n)/2,我们可以求 (m+n - k + 1) largest number,以减
少计算时间。
这个速度比链接上讲的lgm + lgn好些吧。
Given two sorted arrays A, B of size m and n respectively. Find the k-th
smallest element in the union of A and B. You can assume that there are no
duplicate elements.
http://www.leetcode.com/2011/01/find-k-th-smallest-element-in-u
如果A组划k/2,B组划k/2来比较。为方便解释,这里先假设k为偶数,并且m,n>k/2.
如果不满足这些条件,在计算index的时候,会考虑这些情况。
if A[k/2 - 1] == B[k/2 -1] done.
if A[k/2 - 1] > B[k/2 -1]
那么在A[k/2 + 1 - k] 和 B[0 k/2 - 1] 里取k/2 smallest number。
if A[k/2 - 1] < B[k/2 -1] in a similar way
所以是一个recursion问题。而且数组大小按照对半的速度下降。所以是O(lgk)
另外,如果k很大,超过(m+n)/2,我们可以求 (m+n - k + 1) largest number,以减
少计算时间。
这个速度比链接上讲的lgm + lgn好些吧。