File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .ArrayList ;
2
+ import java .util .HashMap ;
3
+ import java .util .List ;
4
+
5
+ class SolutionTwoSum {
6
+ public int [] twoSum (int [] nums , int target ) {
7
+ // ๋ชจ๋ ์๋ฅผ ํด์๋งต์ ์ ์ฅํ๋ค. key = nums[i], value = i
8
+ // ํด์๋งต์ ์ํํ๋ฉฐ target - key = result๋ฅผ ๋ง์กฑํ๋ ์์ ์ฐพ์
9
+ // key ์ result ์ value๋ฅผ ์ ๋ต์ผ๋ก ๋ฐํํ๋ค
10
+ // ์๊ฐ๋ณต์ก๋: O(N), ๊ณต๊ฐ๋ณต์ก๋: O(N)
11
+ // ๊ฐ๋ณ ์ธ๋ฑ์ค ๋ฆฌ์คํธ๋ฅผ ์ ์ฅํ ํด์๋งต
12
+ HashMap <Integer , List <Integer >> indicesByValue = new HashMap <>();
13
+
14
+ for (int i = 0 ; i < nums .length ; i ++) {
15
+ indicesByValue .computeIfAbsent (nums [i ], k -> new ArrayList <>()).add (i );
16
+ }
17
+
18
+ for (int key : indicesByValue .keySet ()) {
19
+ int diff = target - key ;
20
+
21
+ if (indicesByValue .containsKey (diff )) {
22
+ int index1 = indicesByValue .get (key ).get (0 );
23
+
24
+ // ๋์ผํ ๊ฐ์ ๋ํด ๋ ๊ฐ์ ๋ค๋ฅธ ์ธ๋ฑ์ค๊ฐ ์๋์ง ํ์ธ
25
+ int index2 = (key == diff && indicesByValue .get (key ).size () > 1 )
26
+ ? indicesByValue .get (key ).get (1 )
27
+ : indicesByValue .get (diff ).get (0 );
28
+
29
+ return new int []{index1 , index2 };
30
+ }
31
+ }
32
+
33
+ // ์์ ์ฐพ์ง ๋ชปํ ๊ฒฝ์ฐ
34
+ return null ;
35
+ }
36
+ }
You canโt perform that action at this time.
0 commit comments