File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .Map ;
2+ import java .util .HashMap ;
3+
4+ class Solution {
5+ // 정수 배열 nums와 정수 target가 주어질 때 두 정수의 합이 target이 되는 배열 요소의 인덱스를 반환
6+ // 입력받은 배열에는 하나의 해답만 존재한다고 가정할 수 있으며 같은 요소를 한 번 이상 사용할 수는 없다.
7+ // 반환하는 인덱스의 정렬은 신경쓰지 않아도 된다.
8+
9+ public int [] twoSum (int [] nums , int target ) {
10+
11+ // 힌트를 참고하여 시간 복잡도 O(n^2) 이하로 줄이기
12+ // 힌트: Like maybe a hash map to speed up the search?
13+
14+ int [] answer = new int [2 ];
15+
16+ Map <Integer , Integer > numMap = new HashMap <>();
17+
18+ for (int i = 0 ; i < nums .length ; i ++) {
19+ if (numMap .containsKey (target - nums [i ])) {
20+ answer [0 ] = numMap .get (target - nums [i ]);
21+ answer [1 ] = i ;
22+ break ;
23+ }
24+ numMap .put (nums [i ], i );
25+ }
26+
27+ return answer ;
28+
29+ }
30+
31+ // public int[] twoSum(int[] nums, int target) {
32+
33+ // // 전체 탐색 진행
34+ // int[] answer = new int[2];
35+
36+ // for (int i = 0; i < nums.length - 1; i++) {
37+ // for (int j = i + 1; j < nums.length; j++) {
38+ // if (nums[i] + nums[j] == target) {
39+ // answer[0] = i;
40+ // answer[1] = j;
41+ // }
42+ // }
43+ // }
44+
45+ // return answer;
46+ // }
47+
48+ }
You can’t perform that action at this time.
0 commit comments