|
| 1 | +class Solution: |
| 2 | + def twoSum(self, nums: list[int], target: int) -> list[int]: |
| 3 | + num_to_index = {} |
| 4 | + |
| 5 | + for i, num in enumerate(nums): |
| 6 | + diff = target - num |
| 7 | + |
| 8 | + if diff in num_to_index: |
| 9 | + j = num_to_index[diff] |
| 10 | + return [i, j] |
| 11 | + |
| 12 | + num_to_index[num] = i |
| 13 | + |
| 14 | +""" |
| 15 | +================================================================================ |
| 16 | +풀이 과정 |
| 17 | +================================================================================ |
| 18 | +
|
| 19 | +[1차 시도] Brute Force - O(n^2) |
| 20 | +──────────────────────────────────────────────────────────────────────────────── |
| 21 | +1. 단순 반복으로 그냥 문제를 풀어보자. |
| 22 | +2. 단 같은 숫자일 경우에는 넘어가자. |
| 23 | +
|
| 24 | + for i in range(len(nums)): |
| 25 | + for j in range(len(nums)): |
| 26 | + if i == j: |
| 27 | + continue |
| 28 | + if nums[i] + nums[j] == target: |
| 29 | + return [i, j] |
| 30 | +
|
| 31 | +3. O(n^2) 으로 문제를 풀었는데 |
| 32 | +4. 시간이 오래걸리니까 다른 풀이 방법이 있는 것 같음 |
| 33 | +
|
| 34 | +
|
| 35 | +[2차 시도] Hash Table - Two Pass |
| 36 | +──────────────────────────────────────────────────────────────────────────────── |
| 37 | +5. 해싱으로 문제를 풀 방법이 있으려나? |
| 38 | +6. 넘버마다 인덱스를 저장하고 |
| 39 | +7. target에서 현재 가진 값을 뺀 값이 nums에 있는지를 판단하면 될 것 같은데? |
| 40 | +8. 그리고 현재 가진 값과 뺀 값의 인덱스를 그대로 반환하면 될 것 같고 |
| 41 | +9. 근데 동일한 인덱스는 제외해야할듯 |
| 42 | +
|
| 43 | + num_index_dict = defaultdict() |
| 44 | + for index, num in enumerate(nums): |
| 45 | + num_index_dict[num]=index |
| 46 | + print(num_index_dict) |
| 47 | +
|
| 48 | + for index, num in enumerate(nums): |
| 49 | + if (target - num) in nums and num_index_dict[target - num] != index: |
| 50 | + return [index, num_index_dict[target-num]] |
| 51 | +
|
| 52 | +
|
| 53 | +[3차 시도] Hash Table - One Pass |
| 54 | +──────────────────────────────────────────────────────────────────────────────── |
| 55 | +10. 단 한 번의 루프에서도 동작시킬 수 있을듯? |
| 56 | +
|
| 57 | + num_index_dict = defaultdict() |
| 58 | +
|
| 59 | + for index, num in enumerate(nums): |
| 60 | + if (target - num) in num_index_dict: |
| 61 | + return [index, num_index_dict[target - num]] |
| 62 | +
|
| 63 | + num_index_dict[num] = index |
| 64 | +
|
| 65 | +
|
| 66 | +[최종 개선] 코드 가독성 향상 |
| 67 | +──────────────────────────────────────────────────────────────────────────────── |
| 68 | +11. 속도가 많이 빨라졌다. 코드 가독성만 높여보자 |
| 69 | +
|
| 70 | + num_to_index = {} |
| 71 | + |
| 72 | + for i, num in enumerate(nums): |
| 73 | + diff = target - num |
| 74 | +
|
| 75 | + if diff in num_to_index: |
| 76 | + j = num_to_index[diff] |
| 77 | + return [i, j] |
| 78 | + |
| 79 | + num_to_index[num] = i |
| 80 | +""" |
0 commit comments