[英]Find all combinations that gives the result A[i]+B[j]=C[k] with 3 arrays at O[n^2]
There are 3 arrays, every array has a size of N
. 有3个数组,每个数组的大小为
N
Find the combinations that give A[i]+B[j]=C[k]
at only O[n^2]. 找出仅在O [n ^ 2]处给出
A[i]+B[j]=C[k]
]的组合。
There is a simpler problem: given two arrays and a number find all combinations from the arrays which give sum=number. 有一个更简单的问题:给定两个数组和一个数字,从给出sum = number的数组中查找所有组合。 It can be solved in O(n).
可以在O(n)中求解。
We can use its solution as part of solution for the larger one: 我们可以将其解决方案用作更大的解决方案的一部分:
(I'm assuming that all elements are different - it simplifies things a bit) (我假设所有元素都是不同的,这使事情简化了一点)
sort(A)
sort(B)
sort(C)
for(int indexC=0;indexC<N;++indexC)
int indexA=0
int indexB=N-1
while(indexA<0)
//find all combinations in A,B with sum=C[indexC]
int sum=A[indexA]+B[indexB]
if(sum==C[indexC])
OutputCombination(indexA,indexB,indexC)
if(sum<C[indexC])
++indexA
else if(sum>C[indexC])
--indexB
else
++indexA
--indexB
Update : Question was later modified to ask specifically for an implementation in Java. 更新 :后来修改了问题,以专门要求Java实现。 The algorithm and explanation in Python remain valid, but I've also added Java implementation below.
Python中的算法和解释仍然有效,但我还在下面添加了Java实现。
Use a hashmap (or a set) to test for existence in C
with time complexity O(1)
(on average). 使用哈希图 (或集合)测试
C
是否存在,时间复杂度为O(1)
(平均)。 Then all you need is to iterate over all pairs (a,b) | a <- A, b <- B
然后,您需要遍历所有对
(a,b) | a <- A, b <- B
(a,b) | a <- A, b <- B
, for a total time complexity of O(n^2)
. (a,b) | a <- A, b <- B
,总时间复杂度为O(n^2)
。
For example, in Python you could do it like this: 例如,在Python中,您可以这样做:
c = set(C)
for a in A:
for b in B:
if a + b in c:
print a, b, a + b
Quick test: 快速测试:
>>> A = [1,2,3]
>>> B = [3,4,5]
>>> C = [1,4,7]
>>> c = set(C)
>>> for a in A:
... for b in B:
... if a + b in c:
... print a, b, a + b
...
1 3 4
2 5 7
3 4 7
Or, a shorter version with a list comprehension: 或者,使用列表理解的简短版本:
>>> c = set(C)
>>> [(a,b,a+b) for a in A for b in B if a+b in c]
[(1, 3, 4), (2, 5, 7), (3, 4, 7)]
The Java implementation is essentially the same. Java实现本质上是相同的。 The key observation is to use
java.util.HashSet
for checking if the sum A[i]+B[j]
is present in the array C
: 关键观察是使用
java.util.HashSet
来检查数组C
是否存在总和A[i]+B[j]
:
import java.util.HashSet;
class Pairs {
public static void main(String[] args) {
Integer[] A = new Integer[]{1,2,3};
Integer[] B = new Integer[]{3,4,5};
Integer[] C = new Integer[]{1,4,7};
HashSet<Integer> c = new HashSet<Integer>();
for (int i = 0; i < C.length; i++) {
c.add(C[i]);
}
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
if (c.contains(A[i] + B[j])) {
System.out.format("%d %d %d%n", A[i], B[j], A[i]+B[j]);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.