1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import java.util.*;
class Program { public static int[] twoNumberSum(int[] array, int targetSum) { for(int i = 0; i < array.length; i++) { for(int j = i + 1; j < array.length; j++) { if(array[i] + array[j] == targetSum) { return new int[]{array[i], array[j]}; } } } return new int[0]; } }
|
Time complexity O(n^2)
HashMap Time complexity O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import java.util.*;
class Program { public static int[] twoNumberSum(int[] array, int targetSum) { HashMap<Integer, Integer> nums = new HashMap<>(); for(int num : array) { int ans = targetSum - num; if(nums.containsKey(ans)) { return new int[] {ans, num}; } else { nums.put(num,num); } } return new int[0]; } }
|