import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static List<Integer> findSum(List<Integer> l, int sum)
{
Map<Integer, Integer> hm = new HashMap<>();
List<Integer> result = new ArrayList<>();
for(int i=0;i<l.size();i++)
{
int k = sum-l.get(i);
if(hm.containsKey(k))
{
result.add(hm.get(k));
result.add(i);
break;
}
else
hm.put(l.get(i), i);
}
return result;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
List<Integer> l = new ArrayList<>();
l.add(5);
l.add(2);
l.add(12);
l.add(7);
l.add(23);
l.add(4);
Integer sum = 9;
List<Integer> result = findSum(l, sum);
System.out.println("The indexes in the array " + l + " that adds upto sum=" + sum + " are " + result);
}
}
No comments:
Post a Comment