Skip to content

Commit fa623a4

Browse files
committed
solve two-sum
1 parent 36bdbb8 commit fa623a4

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

two-sum/samcho0608.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
for(int i = 0; i < nums.length; i++) {
20+
int numI = nums[i];
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

Comments
 (0)