Skip to content

Commit b93cecd

Browse files
committed
solve #1
O(n^2) ๋กœ ํ†ต๊ณผ๋˜์ง€๋งŒ O(n)
1 parent 67d94fe commit b93cecd

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

โ€Žtwo-sum/mumunuu.javaโ€Ž

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
}

0 commit comments

Comments
ย (0)