Find all pairs of integers within an array which sum to a specified value

前端 未结 15 2025
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 08:00

Design an algorithm to find all pairs of integers within an array which sum to a specified value.

I have tried this problem using a hash

15条回答
  •  鱼传尺愫
    2020-12-01 08:31

    You don't even need to store all the elements in hashmap, and then scan. You can scan during the first iteration itself.

    void foo(int[] A, int sum) {
        HashSet set = new HashSet();
        for (int e : A) {
            if (set.contains(sum-e)) {
                System.out.println(e + "," + (sum-e));
                // deal with the duplicated case
                set.remove(sum-e);
            } else {
                set.add(e);
            }
        }
    }
    

提交回复
热议问题