首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何比较时间复杂度小于O(n^2)的两个数组中的每个元素

如何比较时间复杂度小于O(n^2)的两个数组中的每个元素
EN

Stack Overflow用户
提问于 2018-11-03 20:44:43
回答 2查看 8.2K关注 0票数 3

假设我们有两个数组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。

如果你能提供一些伪码,这将是最好的。

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-03 21:27:38

您可以在O(nlogn)复杂度中执行上述算法,其中n是问题中给出的数组A和数组B的长度。

算法

代码语言:javascript
复制
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)

希望这能有所帮助!

票数 5
EN

Stack Overflow用户

发布于 2018-11-03 21:25:31

这两个列表都需要按升序排序才能工作。

排序费用O(原木n)。而大O运算意味着做两次仍然是O(n log n)。我假设它们已经被整理好了。下面剩下的工作不会影响大O成本。

有一个名为B数组的索引名为indexB,值为零(我的伪代码将使用基于零的索引)。indexAA也是从零开始的。

代码语言:javascript
复制
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)

代码语言:javascript
复制
            // 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));
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53135373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档