st0le
6/29/2013 - 11:42 PM

Linear Solution to 2SUM with Hash Set

Linear Solution to 2SUM with Hash Set

    // Complexity - O(n), Space Complexity - O(n)
    private int[] findPair_3(int[] A) {
        Set<Integer> set = new HashSet<Integer>();
        for (int i = 0, l = A.length; i < l; i++) {
            if (set.contains(-A[i]))
                return new int[]{A[i], -A[i]};
            else
                set.add(A[i]);
        }
        return null;
    }