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.  
  11. public static int[] findTwoSum(int[] nums, int target) {
  12. HashMap<Integer, Integer> map = new HashMap<>();
  13.  
  14. for (int i = 0; i < nums.length; i++) {
  15. int complement = target - nums[i];
  16.  
  17. if (map.containsKey(complement)) {
  18. return new int[] { map.get(complement), i };
  19. }
  20.  
  21. map.put(nums[i], i);
  22. }
  23.  
  24. return new int[] {}; // No solution found
  25. }
  26.  
  27. public static void main(String[] args) {
  28. int[] nums = {2, 7, 11, 15};
  29. int target = 9;
  30.  
  31. int[] result = findTwoSum(nums, target);
  32. if (result.length == 2) {
  33. System.out.println("Indices: " + result[0] + ", " + result[1]);
  34. } else {
  35. System.out.println("No solution found.");
  36. }
  37. }
  38. }
  39.  
  40.  
Success #stdin #stdout 0.15s 55576KB
stdin
Standard input is empty
stdout
Indices: 0, 1