Set A = [2, 10, 5, 9] = sum[A] 26
Set B = [1, 10, 4, 9] = sum[B] 24
Find two elements a, b from set A and B such that
sum[A] - a + b = sum [B] - b + a
I solved this problem in O(n^2).
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(sumOfA - A[i] + B[j] == sumOfB + A[i] - B[j]){
System.out.println("solution: " + A[i] + ", " + B[j])
return;
}
}
}
How it can be improved to O(n)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…