I felt like doing an algorithm and found this problem on leetcode
Given an array of integers, find two numbers such that they add up to a specific target num
Here is the answer using HashMap in java with two passes of the array. Assuming that there are no duplicate elements in the array and there is exactly one solution exists.
import java.util.HashMap;
public class TwoSum {
int[] index = new int[2];
public int[] twoSum(int[] nums, int target)
{
int length = nums.length;
//initialize return values assuming that pair for the given target
//doesn't exist
index[0]=-1;
index[1]=-1;
//sanity check
if(length<1) return index;
HashMap numHash = new HashMap<>(length);
//get the values from array into HashMap assuming that there aren't duplicate values
for(int i=0; i