add Two Sum task

This commit is contained in:
2026-01-28 12:57:58 +03:00
parent 8190c5d607
commit 8bdba1f2f2
5 changed files with 137 additions and 0 deletions

35
Two Sum/Solution.java Normal file
View File

@@ -0,0 +1,35 @@
import java.util.Arrays;
import java.util.HashMap;
class Solution {
public static void main(String[] args) {
int[] test1 = {2, 7, 11, 15}; int target1 = 9;
int[] test2 = {3, 2, 4}; int target2 = 6;
int[] test3 = {3, 3}; int target3 = 6;
System.out.println("twoSum( " + Arrays.toString(test1) + ", " + target1 + " ): " + Arrays.toString(twoSum(test1, target1)));
System.out.println("twoSum( " + Arrays.toString(test2) + ", " + target2 + " ): " + Arrays.toString(twoSum(test2, target2)));
System.out.println("twoSum( " + Arrays.toString(test3) + ", " + target3 + " ): " + Arrays.toString(twoSum(test3, target3)));
}
static int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
HashMap<Integer, Integer> d = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
var remainderIdx = d.get(target - nums[i]);
if (remainderIdx != null) {
res[0] = i;
res[1] = remainderIdx;
return res;
} else {
d.put(nums[i], i);
}
}
return res;
}
}