File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-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+ class Solution {
5+ /**
6+ * ๋ฐฐ์ด์ ์์ 2๊ฐ๋ฅผ ๋ํด์ target ์ซ์๋ค์ ๋ง๋ค๊ณ ์ธ๋ฑ์ค๋ฅผ ๋ฐํ
7+ * ๊ฐ์ ์ซ์๋ฅผ ์ฌ๋ฌ๋ฒ ์ฌ์ฉํ ์ ์๊ณ , ํด๋ต์ ๋ฐ๋์ ์กด์ฌํจ
8+ * Follow-up: Can you come up with an algorithm that is less than O(n^2) time complexity?
9+ */
10+
11+ /*
12+ // naive ํ ํ์ด๋ฒ. O(n^2)
13+ public int[] twoSum(int[] nums, int target) {
14+ // naive ํ ๋ฐฉ๋ฒ: ๋๋ฅผ ์ ์ธํ ๋๋จธ์ง ์ซ์๊ฐ ์๋์ง ์ฐพ์
15+ for (int i=0; i<nums.length-1; i++) {
16+ for (int k=i+1; k<nums.length; k++) {
17+ if (nums[i] + nums[k] == target) {
18+ return new int[]{i,k};
19+ }
20+ }
21+ }
22+ return new int[]{};
23+ }
24+ */
25+
26+
27+ // ์ฒ์์ Map<Integer, List<Integer>>๋ผ๊ณ ์๊ฐํ์ง๋ง ๊ทธ๋ฅ Integer, Integer๋ก ๊ฐ๋ฅํจ
28+ public int [] twoSum (int [] nums , int target ) {
29+
30+ Map <Integer , Integer > map = new HashMap <>();
31+
32+ for (int i = 0 ; i < nums .length ; i ++) {
33+
34+ int needValue = target - nums [i ];
35+ if (map .containsKey (needValue )) {
36+ return new int []{map .get (needValue ), i };
37+ }
38+ map .put (nums [i ], i ); // ํญ์ ํ์ฌ ์ธ๋ฑ์ค๋ฅผ ๋์ค์ ์ ์ฅ
39+
40+ }
41+
42+ return new int []{}; // ์ ๋ ๋๋ฌํ์ง ์์ (๋ฌธ์ ์กฐ๊ฑด์ ์ ๋ต์ด ํญ์ ์กด์ฌ)
43+
44+ }
45+
46+
47+ }
You canโt perform that action at this time.
0 commit comments