假设我们有两个数组a和bn,目标是将A中的每个元素与B中的元素进行比较,然后返回一个列表结果万亿,它记录A中比B中的每个元素的数量。
例如,
A= 38、24、43、3、B= 9、82、10、11
因为38大于9,10和11,所以结果是3,那么结果是3,3,3,0。
如果你能提供一些伪码,这将是最好的。
谢谢。
发布于 2018-11-03 21:27:38
您可以在O(nlogn)复杂度中执行上述算法,其中n是问题中给出的数组A和数组B的长度。
算法
1. Sort both the arrays A and B, this will take O(nlogn) time complexity.
2. Take two pointers i and j, initialize both of them to 0. we will use i for array A and j for B.
3. Create a result array res of size n.
4. Start a while loop
while(i<n && j<n) {
if(A[i] > B[j]) {
j++;
} else {
res[i] = j+1;
i++;
}
}
5. while(i<n) {
res[i] = n;
}
This step is for the case where all elements in A are bigger than all elements in B.最后,您将准备好res数组和答案。
总体时间复杂度- O(nlogn)。
希望这能有所帮助!
发布于 2018-11-03 21:25:31
这两个列表都需要按升序排序才能工作。
排序费用O(原木n)。而大O运算意味着做两次仍然是O(n log n)。我假设它们已经被整理好了。下面剩下的工作不会影响大O成本。
有一个名为B数组的索引名为indexB,值为零(我的伪代码将使用基于零的索引)。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));https://stackoverflow.com/questions/53135373
复制相似问题