Find a pair of elements from an array whose sum equals a given number

后端 未结 30 1056
暗喜
暗喜 2020-11-22 10:14

Given array of n integers and given a number X, find all the unique pairs of elements (a,b), whose summation is equal to X.

The following is my solution, it is O(nLo

30条回答
  •  伪装坚强ぢ
    2020-11-22 10:43

    Solution in java. You can add all the String elements to an ArrayList of strings and return the list. Here I am just printing it out.

    void numberPairsForSum(int[] array, int sum) {
        HashSet set = new HashSet();
        for (int num : array) {
            if (set.contains(sum - num)) {
                String s = num + ", " + (sum - num) + " add up to " + sum;
                System.out.println(s);
            }
            set.add(num);
        }
    }
    

提交回复
热议问题