File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .HashMap ;
2
+ import java .util .HashSet ;
3
+
4
+ class Solution {
5
+ public int [] twoSum (int [] nums , int target ) {
6
+ // // O(N^2)
7
+ // for (int i =0; i< nums.length-1; i++) {
8
+ // for (int j=i+1; j<nums.length; j++) {
9
+ // if (nums[i] + nums[j] == target)
10
+ // return new int[] {i, j};
11
+ // }
12
+ // }
13
+ // return null;
14
+
15
+ // O(N)
16
+ // HashMap 사용
17
+ HashMap <Integer , Integer > map = new HashMap <>();
18
+ for (int i =0 ; i <nums .length ; i ++) {
19
+ map .putIfAbsent (nums [i ], i );
20
+ }
21
+
22
+ for (int i =0 ; i <nums .length ; i ++) {
23
+ int num = nums [i ];
24
+ int anoterNum = target - num ;
25
+ if (map .containsKey (anoterNum ) && i !=map .get (anoterNum ))
26
+ return new int [] {i , map .get (anoterNum )};
27
+ }
28
+ return null ;
29
+ }
30
+ }
31
+
You can’t perform that action at this time.
0 commit comments