File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ 브루트 포스틑 이중 반복문을 사용하므로 시간 복잡도가 O(n^2)
3+ -> map에 (값, 인덱스)로 저장 후 배열을 반복하며 합이 target인 값을 찾는다.
4+ */
5+ import java .util .HashMap ;
6+ import java .util .Map ;
7+
8+ class Solution {
9+ public int [] twoSum (int [] nums , int target ) {
10+ Map <Integer , Integer > numberMap = new HashMap <>();
11+ for (int i =0 ; i <nums .length ; i ++) {
12+ numberMap .put (nums [i ], i );
13+ }
14+
15+ for (int i =0 ; i <nums .length ; i ++) {
16+ int operand = target - nums [i ];
17+ if (numberMap .containsKey (operand ) && numberMap .get (operand ) != i ) { // 자기 자신은 제외
18+ return new int [] { numberMap .get (target - nums [i ]), i };
19+ }
20+ }
21+
22+ return new int [] {};
23+ }
24+ }
25+
26+ /*
127class Solution {
228 public int[] twoSum(int[] nums, int target) {
329 for (int i=0; i<nums.length-1; i++) {
@@ -11,3 +37,4 @@ public int[] twoSum(int[] nums, int target) {
1137 return new int[] {};
1238 }
1339}
40+ */
You can’t perform that action at this time.
0 commit comments