如何解决如何比较两个数组中每个元素的时间复杂度小于On ^ 2
您可以以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)
。
希望这可以帮助!
解决方法
假设我们有两个数组A [n]和b
[n],目标是将A中的每个元素与B中的元素进行比较。然后返回一个列表结果[n],该结果记录了A中每个元素的数量大于B中的元素。
例如,
A = [38,24,43,3],B = [9,82,10,11]
由于38大于9、10和11,因此result [0]为3。然后结果为[3、3、3、0]。
如果您可以提供一些伪代码,那将是最好的。
谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。