Untitled

mail@pastecode.io avatar
unknown
java
2 years ago
1.4 kB
3
Indexable
Never
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class LuxsoftTask {
    /**
     * Write java function which calculates number of pairs in array.
     * Pair is when two numbers added together, result is zero.
     * Please consider only first occurance of a each Pair
     * a={1,2,3,4,1,-1,1,-1,-2,2,2,-2,3,4}
     */
    public static void main(String[] args) {
        Integer data[] = {1,2,3,4,1,-1,-2,2,2,-2,3,4};
        //int pairCount = getPairCount(data);
        int pairCount = getPairCountSetSolution(data);
        System.out.println(pairCount);
    }

    public static int getPairCount(Integer[] data) {
        int count = 0;
        for (int i = 0; i < data.length; i++) {
            for (int j = i+1; j < data.length; j++) {
                if (data[i] + data[j] == 0 && data[i] != 0) {
                    count++;
                    data[i] = 0;
                    data[j] = 0;
                }
            }
        }
        return count;
    }

    public static int getPairCountSetSolution(Integer[] data) {
        int count = 0;
        Set<Integer> nums = new HashSet<>();
        for (Integer i: data) {
            if (nums.contains(-i)) {
                nums.remove(-i);
                count++;
            } else {
                nums.add(i);
            }
        }

        return count;
    }


}