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

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

    Implementation in Java : Using codaddict's algorithm:

    import java.util.Hashtable;
    public class Range {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Hashtable mapping = new Hashtable();
        int a[]= {80,79,82,81,84,83,85};
        int k = 160;
    
        for (int i=0; i < a.length; i++){
            mapping.put(a[i], i);
        }
    
        for (int i=0; i < a.length; i++){
            if (mapping.containsKey(k - a[i]) && (Integer)mapping.get(k-a[i]) != i){
                System.out.println(k-a[i]+", "+ a[i]);
            }
        }      
    
    }
    
    }
    

    Output:

    81, 79
    79, 81
    

    If you want duplicate pairs (eg: 80,80) also then just remove && (Integer)mapping.get(k-a[i]) != i from the if condition and you are good to go.

提交回复
热议问题