Thursday, October 15, 2015

Java - Finding K-complementary Pairs in Array of Integers

October 15, 2015 - I was bored so I went to play around with Java and solve some simple problem or exercise below to energize my playful mind.

Write an efficient algorithm to find K-complementary pairs in a given array of integers. Given Array A, pair (i, j) is K- complementary if K = A[i] + A[j];


Solution:

    public Set<ComplementaryPair> findComplementaryPairs(int sum, int[] numbers) {

        if (numbers == null || numbers.length < 2) {
            return new HashSet<>();
        }

        Set<Integer> noneDuplicate = new HashSet<>();
        for(int number:numbers) {
            noneDuplicate.add(number);
        }

        Set<ComplementaryPair> complementaryPairs = new HashSet<>();
        for (Integer number: noneDuplicate) {
            if (number > sum) {
                continue;
            }

            int difference = sum - number;
            if (noneDuplicate.contains(difference)) {
                complementaryPairs.add(new ComplementaryPair(number, difference));
            }
        }

        return complementaryPairs;

    }

I may be wrong but hopefully I got this right. Feel free to comment or let me know your thoughts.

No comments:

Post a Comment