Skip to content

Commit 5ed2589

Browse files
committed
Add two sum solution - s0ooo0k
1 parent 53ce7c7 commit 5ed2589

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

two-sum/s0ooo0k.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.util.Map;
2+
3+
class Solution {
4+
5+
/*
6+
* 시간복잡ㄷ도 개선
7+
*
8+
* 시간복잡도 O(n)
9+
* 공간복잡도 O(n)
10+
*/
11+
public int[] twoSum(int[] nums, int target) {
12+
Map<Integer, Integer> arr = new HashMap<>();
13+
14+
for(int i=0; i<nums.length; i++) {
15+
if(arr.containsKey(target-nums[i])) {
16+
return new int[]{arr.get(target-nums[i]), i};
17+
}
18+
arr.put(nums[i], i);
19+
}
20+
return new int[]{0, 0};
21+
}
22+
23+
24+
25+
/*
26+
* 기존 풀이
27+
*
28+
* 시간복잡도 O(n^2)
29+
* 공간복잡도 O(1)
30+
*/
31+
32+
/*
33+
public int[] twoSum(int[] nums, int target) {
34+
int[] answer = new int[2];
35+
for(int i=0; i<nums.length; i++) {
36+
for(int j=i+1; j<nums.length; j++) {
37+
if(nums[i]+nums[j]==target) {
38+
answer[0]=i;
39+
answer[1]=j;
40+
return answer;
41+
}
42+
}
43+
}
44+
return answer;
45+
}
46+
*/
47+
48+
}

0 commit comments

Comments
 (0)