forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdohyeon2.java
More file actions
32 lines (28 loc) · 1.08 KB
/
dohyeon2.java
File metadata and controls
32 lines (28 loc) · 1.08 KB
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
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
// Approach : using HashMap to get index with the element in O(n) time
// complexity
// SpaceComplexity is also O(n)
HashMap<Integer, Integer> numIndexMap = new HashMap<Integer, Integer>();
// Make key and value HashMap
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
numIndexMap.put(num, i);
}
// Search for the other operand looping nums
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
int operand = target - num;
Integer index = numIndexMap.get(operand);
boolean indexExists = index != null;
boolean indexExistsAndIndexIsNotTheNum = indexExists && i != index;
if (indexExistsAndIndexIsNotTheNum) {
return new int[] { i, index };
}
}
// If the valid answer is always exists this is not needed
// But the compiler don't know about that
return new int[2];
}
}