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

后端 未结 30 1067
暗喜
暗喜 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:40

    One Solution can be this, but not optimul (The complexity of this code is O(n^2)):

    public class FindPairsEqualToSum {
    
    private static int inputSum = 0;
    
    public static List findPairsForSum(int[] inputArray, int sum) {
        List list = new ArrayList();
        List inputList = new ArrayList();
        for (int i : inputArray) {
            inputList.add(i);
        }
        for (int i : inputArray) {
            int tempInt = sum - i;
            if (inputList.contains(tempInt)) {
                String pair = String.valueOf(i + ", " + tempInt);
                list.add(pair);
            }
        }
        return list;
       }
    }
    

提交回复
热议问题