fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. int[] arr = {1,2,3,4,5,6};
  14. int sum = 12;
  15. int[] res = twoElementsSum(arr,sum);
  16. System.out.println("Indices of two elements with sum "+sum+" is "+ res[0]+" and "+res[1]);
  17. }
  18. static int[] twoElementsSum(int[] arr, int sum){
  19.  
  20. HashMap<Integer,Integer> map = new HashMap<>();
  21. int[] res = new int[2];
  22. for(int i=0;i<arr.length;i++){
  23. if(map.containsKey(sum - arr[i])){
  24. res[0] = map.get(sum-arr[i]);
  25. res[1] = i;
  26. return res;
  27. }
  28. map.put(arr[i],i);
  29. }
  30. return new int[]{-1,-1};
  31.  
  32. }
  33. }
Success #stdin #stdout 0.18s 57832KB
stdin
Standard input is empty
stdout
Indices of two elements with sum 12 is -1 and -1