diff --git a/1-two-sum/Solution 2.java b/1-two-sum/Solution 2.java new file mode 100644 index 00000000..644f0ce1 --- /dev/null +++ b/1-two-sum/Solution 2.java @@ -0,0 +1,24 @@ +import java.util.HashMap; +import java.util.Map; + +class Solution { + public int[] twoSum(int[] nums, int target) { + int n = nums.length; + Map complementMap = new HashMap<>(); + + for (int i = 0; i < n; i++) { + int complement = target - nums[i]; + + // Check if the complement exists in the map + if (complementMap.containsKey(complement)) { + return new int[]{complementMap.get(complement), i}; + } + + // If not, add the current element and its index to the map + complementMap.put(nums[i], i); + } + + // No solution found + return new int[]{-1, -1}; + } +} diff --git a/1-two-sum/solution3.java b/1-two-sum/solution3.java new file mode 100644 index 00000000..adfafa76 --- /dev/null +++ b/1-two-sum/solution3.java @@ -0,0 +1,23 @@ +import java.util.Arrays; + +class Solution { + public int[] twoSum(int[] nums, int target) { + int left = 0; + int right = nums.length - 1; + + while (left < right) { + int currentSum = nums[left] + nums[right]; + + if (currentSum == target) { + return new int[]{left, right}; + } else if (currentSum < target) { + left++; + } else { + right--; + } + } + + // No solution found + return new int[]{-1, -1}; + } +}