给定两个数组a和b .Find所有元素对(A1,B1),使得A1属于阵列A和B1属于数组b的总和A1 + B1 = K [英] Given two arrays a and b .Find all pairs of elements (a1,b1) such that a1 belongs to Array A and b1 belongs to Array B whose sum a1+b1 = k
问题描述
我要寻找以下的算法以最少的时间和空间复杂度的解决方案。
I am looking for the solution of following algorithm with minimal time and space complexity.
给定两个数组a和b,找到所有对元件(A1,B1),例如使a1属于阵列A和B1属于阵列乙其总和A1 + B1 = K(任意整数)。
Given two arrays a and b, find all pairs of elements (a1,b1) such that a1 belongs to Array A and b1 belongs to Array B whose sum a1+b1 = k (any integer).
我能拿出为O(n log n)的方法,我们将排序阵列中的一个说A和元素b在阵列B分别,执行二进制搜索的排序数组A的值(KB)
I was able to come up with O(n log n) approach where we will sort one of the array say A and for each of the element b in array B, do binary search on sorted array A for value (K-b) .
我们可以改善它的任何进一步的?
Can we improve it any further?
推荐答案
如果您有可能的最大数目的限制(让我们将其命名为M),那么你可以为O解决方案(M + N)。
If you have a limit on the maximum possible number (let's name it M) then you can have a solution in O(M+n).
假布尔数组,如果元件数KB被标记为如此的条b B检查每一个元素,则标记为A的元素作为真正的全价值。
Boolean array of false and mark as true all value for element of A. Then for each element b of B check if the element number K-b is marked as true.
可以,如果你使用的是哈希映射,而不是一个大阵列改善。但我不会考虑,在这样的问题,哈希映射是一种欺骗行为。
You can improve it if you are using an hash-map instead of a big array. But I would not consider that in this kind of questions hash-map is kind of cheating.
反正它会给你O(n)的插入,然后为O(n)查询,为O(n)的总和。
Anyway it would give you O(n) for insertion and then O(n) for query, O(n) in total.
编辑:
一情况下,这可能是有用的。
One case where this might be useful.
- 您有大小10 ^ 6的未排序的载体,所以它们排序,做比赛是为O(n log n)的,其中n = 10 ^ 6。
- 您需要做的这个操作10 ^ 6次(不同的载体),复杂性为O(N * N * log n)的。
- 最大值为10 ^ 9。
使用我的想法不符合布尔,但整数(递增在每次运行),为您提供了一个复杂性:
Using my idea not with boolean but integer (incremented at each run) gives you a complexity of :
- 在O(10 ^ 9)创建磁盘阵列(也同样的空间复杂度)
- O(N)在每次运行,因此为O(n * n)的总量。
您正在使用更多的空间,但你的一个因素的log(n)〜= 20在这种情况下,增加的速度!
You are using more space but you've increased speed by a factor log(n) ~=20 in this case !
这篇关于给定两个数组a和b .Find所有元素对(A1,B1),使得A1属于阵列A和B1属于数组b的总和A1 + B1 = K的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!