|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +/** |
| 5 | + * @author : Piyush Kumar ( spdpiyush ) |
| 6 | + * <p> |
| 7 | + * Question Link : https://leetcode.com/problems/two-sum/ |
| 8 | + * </p> |
| 9 | + */ |
| 10 | +public class TargetSum { |
| 11 | + |
| 12 | + public static void main(String[] args) { |
| 13 | + Solution solution = new Solution(); |
| 14 | + int[] result = solution.twoSumOptimalApproach(new int[] {3, 2, 4}, 6); |
| 15 | + for (int value: result) { |
| 16 | + System.out.println(value); |
| 17 | + } |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * <p> |
| 23 | + * Brute Force Approach. |
| 24 | + * Time Complexity : O(n * (n-1)) ~ O(n^2) |
| 25 | + * Space Complexity : O(1) |
| 26 | + * </p> |
| 27 | + */ |
| 28 | +class Solution { |
| 29 | + /** |
| 30 | + * <p> |
| 31 | + * Brute Force Approach. |
| 32 | + * Time Complexity : O(n * (n-1)) ~ O(n^2) |
| 33 | + * Space Complexity : O(1) |
| 34 | + * </p> |
| 35 | + */ |
| 36 | + public int[] twoSum(int[] nums, int target) { |
| 37 | + for (int i = 0; i < nums.length - 1; i++) { |
| 38 | + for (int j = i+1; j < nums.length ; j++) { |
| 39 | + if ((nums[i] + nums[j]) == target) { |
| 40 | + return new int[] {i , j}; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + throw new IllegalArgumentException("Target not matched"); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Time Complexity : O(n) |
| 49 | + * @param nums |
| 50 | + * @param target |
| 51 | + * @return int[] |
| 52 | + */ |
| 53 | + public int[] twoSumOptimalApproach(int[] nums, int target) { |
| 54 | + Map<Integer, Integer> map = new HashMap<>(); |
| 55 | + for (int i =0 ; i < nums.length ; i++) { |
| 56 | + map.put(nums[i], i); |
| 57 | + } |
| 58 | + for (int i = 0; i < nums.length; i++) { |
| 59 | + int diff = target - nums[i]; |
| 60 | + if (map.containsKey(diff) && map.get(diff) != i) { |
| 61 | + return new int[] {i, map.get(diff)}; |
| 62 | + } |
| 63 | + } |
| 64 | + throw new IllegalArgumentException("Target Not Matched"); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | + |
0 commit comments