Skip to content

Commit 1041629

Browse files
committed
Solution for Two Sum #219
1 parent 8ae6dff commit 1041629

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

two-sum/dohyeon2.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.HashMap;
2+
3+
class Solution {
4+
public int[] twoSum(int[] nums, int target) {
5+
// Approach : using HashMap to get index with the element in O(n) time complexity
6+
// SpaceComplexity is also O(n)
7+
HashMap<Integer,Integer> numIndexMap = new HashMap<Integer,Integer>();
8+
9+
// Make key and value HashMap
10+
for(int i = 0; i < nums.length; i++){
11+
int num = nums[i];
12+
numIndexMap.put(num,i);
13+
}
14+
15+
// Search for the other operand looping nums
16+
for(int i = 0; i < nums.length; i++){
17+
int num = nums[i];
18+
int operand = target - num;
19+
Integer index = numIndexMap.get(operand);
20+
boolean indexExists = index != null;
21+
boolean indexExistsAndIndexIsNotTheNum = indexExists && i != index;
22+
if(indexExistsAndIndexIsNotTheNum){
23+
// Manual sort
24+
if( i < index){
25+
return new int[]{ i, index };
26+
}else{
27+
return new int[]{ index, i };
28+
}
29+
}
30+
}
31+
32+
// If the valid answer is always exists this is not needed
33+
// But the compiler don't know about that
34+
return new int[2];
35+
}
36+
}

0 commit comments

Comments
 (0)