Skip to content

Commit b1b7a9f

Browse files
Add two-sum
1 parent 1e7753e commit b1b7a9f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

β€Žtwo-sum/changhoon-sung.cppβ€Ž

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
two-sum
3+
μš”κ΅¬μ‚¬ν•­: μ£Όμ–΄μ§„ λ°°μ—΄μ—μ„œ 두 수의 합이 νƒ€κ²Ÿμ„ λ§Œλ“€ 수 μžˆλŠ”μ§€ ν™•μΈν•˜κ³ , ν•΄λ‹Ή μ›μ†Œλ₯Ό λ°˜ν™˜ν•˜λΌ.
4+
μ ‘κ·Ό 1: κ°€μž₯ λ‹¨μˆœν•œ 방법은 μž…λ ₯에 λŒ€ν•΄ λͺ¨λ“  combination을 ν™•μΈν•˜λŠ” κ²ƒμž…λ‹ˆλ‹€.
5+
μ‹œκ°„ λ³΅μž‘λ„λŠ” μž…λ ₯ μŠ€μΊ” O(N)을 N개의 μ›μ†Œμ— λŒ€ν•΄ μˆ˜ν–‰ν•˜λ―€λ‘œ O(N^2)μž…λ‹ˆλ‹€.
6+
곡간 λ³΅μž‘λ„λŠ” μž…λ ₯ 레퍼런슀λ₯Ό κ·ΈλŒ€λ‘œ μ‚¬μš©ν•˜λ©°, μΆ”κ°€λ‘œ μ €μž₯ 및 κ΄€λ¦¬ν•˜λŠ” μžλ£Œκ΅¬μ‘°κ°€ μ—†μœΌλ―€λ‘œ O(1)μž…λ‹ˆλ‹€.
7+
μ ‘κ·Ό 2: ν•œ κ°€μ§€ μ•„μ΄λ””μ–΄λŠ” μž„μ˜μ˜ μž…λ ₯ X에 λŒ€ν•΄ 합이 `target`이 λ˜λ„λ‘ ν•˜λŠ” pairλŠ” μœ μΌν•˜κ²Œ κ²°μ •λœλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€.
8+
λ”°λΌμ„œ, 합을 κ΅¬ν•˜λŠ” λŒ€μ‹ , μ£Όμ–΄μ§„ μž…λ ₯에 λŒ€ν•œ νŽ˜μ–΄ 쑴재 유무λ₯Ό κ²€μ‚¬ν•˜λŠ” κ²ƒμœΌλ‘œ 문제λ₯Ό μ „ν™˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
9+
수의 λ²”μœ„κ°€ μΆ©λΆ„νžˆ ν¬λ―€λ‘œ, λ°°μ—΄ λŒ€μ‹  ν•΄μ‹œ 기반 unordered_set으둜 νŽ˜μ–΄ 쑴재 μ—¬λΆ€ 쿼리 및 μ‚½μž…μ„ O(1)에 μˆ˜ν–‰ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
10+
μ΅œμ•…μ˜ 경우, λͺ¨λ“  μž…λ ₯에 λŒ€ν•΄ unordered_set 쿼리 및 μ‚½μž…μ„ μˆ˜ν–‰ν•˜λ―€λ‘œ 총 μ‹œκ°„ λ³΅μž‘λ„λŠ” O(N), 곡간 λ³΅μž‘λ„λŠ” μž…λ ₯κ³Ό κ°™μœΌλ―€λ‘œ O(N)μž…λ‹ˆλ‹€.
11+
*/
12+
13+
#include <vector>
14+
#include <unordered_set>
15+
16+
class Solution {
17+
public:
18+
std::vector<int> twoSum(std::vector<int>& nums, int target) {
19+
std::unordered_set<int> s;
20+
21+
for(auto it = nums.begin(); it != nums.end(); it++) {
22+
int x = *it;
23+
if (s.find(target - x) != s.end()) {
24+
return std::vector<int>(x, target-x);
25+
} else {
26+
s.insert(x);
27+
}
28+
}
29+
30+
// 문제의 μ‘°κ±΄μ—μ„œ 단 ν•˜λ‚˜μ˜ μ†”λ£¨μ…˜μ΄ λ°˜λ“œμ‹œ μ‘΄μž¬ν•œλ‹€κ³  κ°€μ •ν•˜λ―€λ‘œ, 이곳에 λ„λ‹¬ν•˜μ§€ μ•ŠμŒ.
31+
throw std::runtime_error("No two sum solution found");
32+
}
33+
};

0 commit comments

Comments
Β (0)