鉴于2排序整数数组,找到的第n个数量最多的次线性时间整数、数组、线性、数量最多

2023-09-10 23:45:39 作者:南語

可能重复:   How找到两排序数组的工会第k个最小元素?

这是一个问题,我的一个朋友告诉我,他被要求面试时,我一直在想一个解决方案。

This is a question one of my friends told me he was asked while interviewing, I've been thinking about a solution.

次线性时间意味着对数对我来说,也许某种鸿沟而治之的方法。为简单起见,假设两个阵列的大小相同,并且所有的元素都是唯一的

Sublinear time implies logarithmic to me, so perhaps some kind of divide and conquer method. For simplicity, let's say both arrays are the same size and that all elements are unique

推荐答案

我觉得这是对的子阵 A [0到n-1] 两个并行二进制搜索和 B [0到n-1] ,这是O(log n)的。

I think this is two concurrent binary searches on the subarrays A[0..n-1] and B[0..n-1], which is O(log n).

在给定排序的数组,你知道的第n 的最大的会前或 A [N-1] 如果是在数组中出现的地方 A B [N-1] 如果是在阵列 B 在考虑项目时指数 A A 键,索引项 B B 。 在如下(pretty的粗糙的伪code,没有采取在考虑一次性的问题)执行二进制搜索: 如果 A + B> ñ,然后降低搜索集 如果 A [A]> B〔B] 然后 B = B / 2 ,否则 A = A / 2 Given sorted arrays, you know that the nth largest will appear somewhere before or at A[n-1] if it is in array A, or B[n-1] if it is in array B Consider item at index a in A and item at index b in B. Perform binary search as follows (pretty rough pseudocode, not taking in account 'one-off' problems): If a + b > n, then reduce the search set if A[a] > B[b] then b = b / 2, else a = a / 2 如果 A [A]> B〔B] 然后 B = 3/2 * B ,否则 A = 3/2 *一个(的中间 A 和previous A ) if A[a] > B[b] then b = 3/2 * b, else a = 3/2 * a (halfway between a and previous a)

我相信最坏的情况O(LN N),但在任何情况下,绝对次线性。

I believe worst case O(ln n), but in any case definitely sublinear.