From 3a05073e09ba71abfb99a65ddec71fb5646644d3 Mon Sep 17 00:00:00 2001 From: rajveer-09 <143857709+rajveer-09@users.noreply.github.com> Date: Sun, 3 Dec 2023 19:19:50 +0530 Subject: [PATCH 1/2] Create Solution 2.java --- 1-two-sum/Solution 2.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 1-two-sum/Solution 2.java 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}; + } +} From 158852a0dc1389b0eae0af89daafddc3055233da Mon Sep 17 00:00:00 2001 From: rajveer-09 <143857709+rajveer-09@users.noreply.github.com> Date: Sun, 3 Dec 2023 19:27:51 +0530 Subject: [PATCH 2/2] Create solution3.java --- 1-two-sum/solution3.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 1-two-sum/solution3.java 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}; + } +}