[英]How to compare each element in two arrays with time complexity less than O(n^2)
假設我們有兩個數組 A[n] 和 b[n],目標是將 A 中的每個元素與 B 中的元素進行比較,然后返回一個列表 result[n],其中記錄了 A 中每個元素的個數大於B 中的元素。
例如,
A = [38, 24, 43, 3], B = [9, 82, 10, 11]
由於 38 大於 9、10 和 11,因此 result[0] 為 3。那么 result 為 [3, 3, 3, 0]。
如果能提供一些偽代碼就更好了。
謝謝你。
您可以在 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)
。
希望這可以幫助!
兩個列表都需要升序排序才能工作。
排序成本O(log n) 。 而 big-O 算術意味着做兩次仍然是O(n log n)
。 我假設它們已經排序。 下面的剩余工作不會影響大 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
之后,從indexA
開始, result
所有剩余的項目都比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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.