|
1 | | -import java.util.Scanner; |
2 | | - |
3 | 1 | class TwoSum { |
4 | | - |
5 | | - public static int[] checkTwoSum(int[] nums, int target) { |
6 | | - for(int i=0; i <nums.length; i++){ |
7 | | - for(int j= i+1; j<nums.length; j++){ |
8 | | - if(nums[i]+nums[j]==target){ |
9 | | - int[] arr = {nums[i],nums[j]}; |
10 | | - return arr; |
| 2 | + public int[] twoSumBrute(int[] nums, int target) { // brute-force O(n^2) time |
| 3 | + int n = nums.length; |
| 4 | + int[] result = new int[2]; |
| 5 | + for(int i = 0; i<n; i++){ |
| 6 | + for(int j = 0; j<n; j++){ |
| 7 | + if((nums[i]+nums[j]) == target && (i!=j)){ |
| 8 | + result[0] = i; |
| 9 | + result[1] = j; |
| 10 | + return result; |
11 | 11 | } |
12 | 12 | } |
13 | 13 | } |
14 | | - throw new IllegalArgumentException("No two-sum solution"); |
15 | 14 | } |
16 | 15 |
|
17 | | - public static void main(String[] args){ |
18 | | - Scanner input = new Scanner(System.in); |
19 | | - int target = input.nextInt(); |
20 | | - int n = input.nextInt(); |
21 | | - int[] nums = new int[n]; |
22 | | - for(int i=0; i<n; i++){ |
23 | | - nums[i] = input.nextInt(); |
| 16 | + public int[] twoSumHash(int[] nums, int target) { // 1-Hash approach O(n) time |
| 17 | + Map<Integer, Integer> map = new HashMap<>(); |
| 18 | + int[] result = new int[2]; |
| 19 | + |
| 20 | + for(int i = 0; i<nums.length; i++){ |
| 21 | + int complement = target-nums[i]; |
| 22 | + if(map.containsKey(complement) && map.get(complement)!= i){ |
| 23 | + result[0] = i; |
| 24 | + result[1] = map.get(complement); |
| 25 | + return result; |
| 26 | + } |
| 27 | + map.put(nums[i], i); |
24 | 28 | } |
25 | | - checkTwoSum(nums, target); |
26 | | - } |
| 29 | + } |
| 30 | + |
| 31 | + return result; |
27 | 32 | } |
0 commit comments