Files
leetcode/1. Two Sum/Solution.java
2026-01-28 15:56:45 +03:00

36 lines
1.1 KiB
Java

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;
}
}