forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsamcho0608.java
More file actions
35 lines (30 loc) · 988 Bytes
/
samcho0608.java
File metadata and controls
35 lines (30 loc) · 988 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.HashMap;
import java.util.Map;
// link: https://leetcode.com/problems/two-sum/description/
// difficulty: Easy
class Solution {
// Problem
// * exactly one solution
// * must use index only once
// * return: indices of two numbers that add up to `target`
// Solution:
// * Time Complexity: O(N)
// * Space Complexity: O(N)
public int[] twoSum(int[] nums, int target) {
// Space Complexity: O(N)
Map<Integer, Integer> indexByNum = new HashMap<>();
// Time Complexity: O(N)
for(int i = 0; i < nums.length; i++) {
int numI = nums[i];
indexByNum.put(numI, i);
}
// Time Complexity: O(N)
for(int i = 0; i < nums.length; i++) {
int numI = nums[i];
Integer compl = indexByNum.getOrDefault(target-numI, null);
if(compl != null && i != compl)
return new int[] {i, compl};
}
return null;
}
}