Array

Two sum from array

Pinterest LinkedIn Tumblr
Given an array of elements and sum. The program should displays the array elements which combinations equal to sum.
Write a program to give two sums from the array.

Algorithm Explanation

Pass an array and sum to the utility function.
Use Hashmap to add the sum and index and array to increment index. Return the array of elements which give the sum equal to the sum of elements.
Print the return array.

Source Code

package com.dsacode.DataStructre.array;
 
import java.util.Arrays;
import java.util.HashMap;
 
public class TwoSumArray {
     
    public int[] twoSum(int[] numbers, int target) {
        HashMap < Integer, Integer > map = new HashMap < Integer, Integer > ();
        int[] result = new int[2];
      
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(numbers[i])) {
                int index = map.get(numbers[i]);
                result[0] = index+1 ;
                result[1] = i+1;
                break;
            } else {
                map.put(target - numbers[i], i);
            }
        }
      
        return result;
        }
    public static void main(String[] args) {
        int[] array={2,8,3,9,5,7,3,6};
        System.out.println("List of items form array: "+ Arrays.toString(array));
         
        TwoSumArray ts= new TwoSumArray();
        int []res = ts.twoSum(array, 8);
         
        System.out.println("Sum of two items '8' : "+ Arrays.toString(res));
 
    }
 
}

Output

List of items form array: [2, 8, 3, 9, 5, 7, 3, 6]
Sum of two items '8' : [3, 5]

Write A Comment