Array

Find a pair of elements from an array

Pinterest LinkedIn Tumblr

Data structure Description

Write a program to find a pair of numbers from the array.

Algorithm Explanation

Build array and pass an argument to the utility function. Create a map with two integer argument.
If the map contains array element, Get and increment the count. Otherwise, store in the map.
Print the values.

Source Code

package com.dsacode.DataStructre.array;
 
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
 
public class ArrayPairSum {
 
    public static void getSumPairs(int []input, int k){
        Map < Integer, Integer > pairs = new HashMap < Integer, Integer >();
 
        for(int i = 0; i < input.length; i++){
 
            if(pairs.containsKey(input[i]))
                System.out.println(input[i] +", "+ pairs.get(input[i]) + " = " + k);
            else
                pairs.put(k-input[i], input[i]);
        }
 
    }
     
    public static void main(String[] args) {       
 
        int []array = {2,45,7,3,5,1,8,9};
        System.out.println("The list of array items: "+ Arrays.toString(array));
         
        getSumPairs(array,10);     
 
    }
 
}

Output

The list of array items: [2, 45, 7, 3, 5, 1, 8, 9]
3, 7 = 10
8, 2 = 10
9, 1 = 10

Write A Comment