upd
This commit is contained in:
35
1. Two Sum/Solution.java
Normal file
35
1. Two Sum/Solution.java
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user