Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

algorithm - find two element a and b from set A and B such that on swapping these elements, sum of sets is equal

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put the elements of set A into a structure that allows to test set membership in O(1) (for example a hash table or a bit vector if the range of elements is small). This will run in O(n).

Now iterate through the set B and check if there is an element in A that is the correct distance (half the difference of the sums) away from the element in B. This will also run in O(n).

Here is some pseudo code, where the set A is represented in such a way that the contains operation runs in O(1):

sumA = sum(A);
sumB = sum(B);
foreach (b in B) {
    a = b + (sumA - sumB)/2;
    if (A contains a) {
        return pair(a, b);
    }
}
return "no solution";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...