这两个列表都需要按升序排序才能正常工作。
分拣成本O(log n)。而大 O 算术意味着做两次仍然是O(n log n)。我将假设它们已经排序。下面的剩余工作不会影响 big-O 成本。
有一个名为indexB 的B 数组的索引,值为零(我的伪代码将使用从零开始的索引)。而indexA 代表A 也从零开始。
indexA=0
For each indexB from 0 to B.Length-1
While indexA < A.Length and the value at `A[indexA]` is less than or equal to the value at `B[indexB]`
Set the `result[indexA]` to be `indexB`
Increment `indexA`
Endwhile
Endfor
之后,result 中从indexA 开始的所有剩余项都大于B 中的所有项,因此将其余项设置为B.Length。
在发布我的原始答案 2 年后编辑,添加: 实际 C# 代码以反映上述伪代码。我相信下面的代码是O(n),与首先对数组进行排序的成本相比,这可以忽略不计(在大O 方面),所以总成本仍然是O(n log n)。
// Note: I am simulating pre-sorted arrays, which costs "O(n log n)"...
// The reason for adding this sample code is to help clarify the cost of the
// remaining work (after the sorts) by showing real code, to avoid any
// ambiguity from the pseudocode, even though that's what the OP asked for
var A = new[] { 3, 24, 38, 43 };
var B = new[] { 9, 10, 11, 82 };
var result = new int[4];
int indexA = 0;
for (int indexB = 0; indexB < B.Length; indexB++)
{
while (indexA < A.Length && A[indexA] <= B[indexB])
{
result[indexA] = indexB;
indexA++;
}
}
while (indexA < A.Length)
{
result[indexA] = B.Length;
indexA++;
}
Console.WriteLine(string.Join(", ", result));