We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 36bdbb8 commit fa623a4Copy full SHA for fa623a4
two-sum/samcho0608.java
@@ -0,0 +1,27 @@
1
+import java.util.HashMap;
2
+import java.util.Map;
3
+
4
+class Solution {
5
+ // return: indices of two numbers that add up to `target`
6
+ // * exactly one solution
7
+ // * must use index only once
8
9
+ // Time Complexity: O(n)
10
+ // Space Complexity: O(n)
11
+ public int[] twoSum(int[] nums, int target) {
12
+ Map<Integer, Integer> indexByNum = new HashMap<>();
13
14
+ for(int i = 0; i < nums.length; i++) {
15
+ int numI = nums[i];
16
+ indexByNum.put(numI, i);
17
+ }
18
19
20
21
+ Integer compl = indexByNum.getOrDefault(target-numI, null);
22
+ if(compl != null && i != compl) return new int[] {i, compl};
23
24
25
+ return null;
26
27
+}
0 commit comments