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

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

    Implementation in Java : Using codaddict's algorithm (Maybe slightly different)

    import java.util.HashMap;
    
    public class ArrayPairSum {
    
    
    public static void main(String[] args) {        
    
        int []a = {2,45,7,3,5,1,8,9};
        printSumPairs(a,10);        
    
    }
    
    
    public static void printSumPairs(int []input, int k){
        Map pairs = new HashMap();
    
        for(int i=0;i

    For input = {2,45,7,3,5,1,8,9} and if Sum is 10

    Output pairs:

    3,7 
    8,2
    9,1
    

    Some notes about the solution :

    • We iterate only once through the array --> O(n) time
    • Insertion and lookup time in Hash is O(1).
    • Overall time is O(n), although it uses extra space in terms of hash.

提交回复
热议问题