Skip to content

Commit f3fe4e6

Browse files
two sum solution
1 parent 93deaff commit f3fe4e6

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

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

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

0 commit comments

Comments
ย (0)