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
+ // μκ°λ³΅μ‘λ O(nΒ²)
2
+ // - nums.indexOf()λ λ°°μ΄ μ 체λ₯Ό μννλ O(n) μμ
3
+ // - μ΄ μμ
μ΄ for 루ν(O(n)) λ΄λΆμμ μ€νλλ―λ‘ μ 체 μκ°λ³΅μ‘λλ O(n) * O(n) = O(nΒ²)
4
+ /*var twoSum = function (nums, target) {
5
+ for (let i = 0; i < nums.length; i++) {
6
+ let x = nums.indexOf(target - nums[i]);
7
+ if (x > -1 && x !== i) {
8
+ return [i, x];
9
+ }
10
+ }
11
+ return [];
12
+ };*/
13
+
14
+ // μκ°λ³΅μ‘λ O(n)
15
+ // μ 체 λ°°μ΄μ ν λ²λ§ μν O(n) + ν€-κ° μ μ μ₯μ O(1)
16
+ // Map λμ κ°μ²΄(Object)λ₯Ό μ¬μ©ν΄λ λ λ― ν¨
17
+ // => μΌλ° κ°μ²΄λ {}, μ κ·Όμ obj[key]λ‘ κ°λ₯, has() λμ (key in obj) λλ obj[key] !== undefined μ¬μ© κ°λ₯
18
+ var twoSum = function ( nums , target ) {
19
+ let minus = new Map ( ) ;
20
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
21
+ let current = nums [ i ] ;
22
+
23
+ // νμ¬ μ«μκ° μ΄μ μ μ μ₯λ 보μ(complement)μ μΌμΉνλμ§ νμΈ - Map κ°μ²΄μ hasλ O(1) μ°μ°
24
+ if ( minus . has ( current ) ) {
25
+ return [ minus . get ( current ) , i ] ;
26
+ }
27
+
28
+ // νμ¬ μ«μμ 보μ(target-current)μ μΈλ±μ€λ₯Ό λ§΅μ μ μ₯ - Map κ°μ²΄μ setμ O(1) μ°μ°
29
+ minus . set ( target - current , i ) ;
30
+ }
31
+
32
+ return [ ] ;
33
+ } ;
You canβt perform that action at this time.
0 commit comments