File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .HashMap ;
2
+ import java .util .Map ;
3
+
4
+ /**
5
+ 본래 brute force로 이중 for문으로 풀었다가 map으로 최적화.
6
+ */
7
+ class Solution {
8
+ /**
9
+ * brute force 풀이
10
+ */
11
+ // public int[] twoSumByBruteForce(int[] nums, int target) {
12
+ // for (int i = 0; i < nums.length; i++) {
13
+ // for (int j = i+1; j < nums.length; j++) {
14
+ // if (nums[i] + nums[j] == target) {
15
+ // return new int[] { i, j };
16
+ // }
17
+ // }
18
+ // }
19
+ // return new int[2];
20
+ // }
21
+
22
+ public int [] twoSum (int [] nums , int target ) {
23
+ Map <Integer , Integer > numberMap = new HashMap <>();
24
+ for (int i = 0 ; i < nums .length ; i ++) {
25
+ int required = target - nums [i ];
26
+ Integer index = numberMap .get (required );
27
+
28
+ if (index != null ) {
29
+ return new int [] { index , i };
30
+ }
31
+ numberMap .put (nums [i ], i );
32
+ }
33
+ return new int [2 ];
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments