@@ -35,4 +35,66 @@ You can return the answer in any order.
3535* <code >-10<sup >9</sup > <= target <= 10<sup >9</sup ></code >
3636* ** Only one valid answer exists.**
3737
38- ** Follow-up:** Can you come up with an algorithm that is less than <code >O(n<sup >2</sup >)</code > time complexity?
38+ ** Follow-up:** Can you come up with an algorithm that is less than <code >O(n<sup >2</sup >)</code > time complexity?
39+
40+ To solve the Two Sum problem in Java using a ` Solution ` class, we'll follow these steps:
41+
42+ 1 . Define a ` Solution ` class with a method named ` twoSum ` .
43+ 2 . Inside the ` twoSum ` method, create a hashmap to store elements and their indices.
44+ 3 . Iterate through the array:
45+ - For each element, calculate the complement required to reach the target sum.
46+ - Check if the complement exists in the hashmap.
47+ - If found, return the indices of the current element and the complement.
48+ - If not found, add the current element and its index to the hashmap.
49+ 4 . Handle edge cases:
50+ - If no solution is found, return an empty array or null (depending on the problem requirements).
51+
52+ Here's the implementation:
53+
54+ ``` java
55+ import java.util.HashMap ;
56+
57+ public class Solution {
58+
59+ public int [] twoSum (int [] nums , int target ) {
60+ // Create a hashmap to store elements and their indices
61+ HashMap<Integer , Integer > map = new HashMap<> ();
62+
63+ // Iterate through the array
64+ for (int i = 0 ; i < nums. length; i++ ) {
65+ int complement = target - nums[i];
66+ // Check if the complement exists in the hashmap
67+ if (map. containsKey(complement)) {
68+ // Return the indices of the current element and the complement
69+ return new int []{map. get(complement), i};
70+ }
71+ // Add the current element and its index to the hashmap
72+ map. put(nums[i], i);
73+ }
74+ // If no solution is found, return an empty array or null
75+ return new int []{};
76+ }
77+
78+ public static void main (String [] args ) {
79+ Solution solution = new Solution ();
80+
81+ // Test cases
82+ int [] nums1 = {2 , 7 , 11 , 15 };
83+ int target1 = 9 ;
84+ int [] result1 = solution. twoSum(nums1, target1);
85+ System . out. println(" Example 1 Output: [" + result1[0 ] + " , " + result1[1 ] + " ]" );
86+
87+ int [] nums2 = {3 , 2 , 4 };
88+ int target2 = 6 ;
89+ int [] result2 = solution. twoSum(nums2, target2);
90+ System . out. println(" Example 2 Output: [" + result2[0 ] + " , " + result2[1 ] + " ]" );
91+
92+ int [] nums3 = {3 , 3 };
93+ int target3 = 6 ;
94+ int [] result3 = solution. twoSum(nums3, target3);
95+ System . out. println(" Example 3 Output: [" + result3[0 ] + " , " + result3[1 ] + " ]" );
96+ }
97+ }
98+ ```
99+
100+ This implementation provides a solution to the Two Sum problem with a time complexity of O(n), where n is the number of elements in the input array.
0 commit comments