File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You canβt perform that action at this time.
0 commit comments