|
| 1 | +""" |
| 2 | +[결과 요약] |
| 3 | +# 재시도횟수: 3회 |
| 4 | + 1. 배열의 모든 경우의 수 계산하기 |
| 5 | + - 시간복잡도 O(n^2) |
| 6 | + 2. 전체 반복하지 않고 인덱스 기준 뒤만 반복하기 |
| 7 | + - O(n^2)이지만 약간 더 효율적 |
| 8 | + 3. 딕셔너리(Map) 사용 |
| 9 | + - 시간복잡도: O(n) / 공간복잡도: O(n) |
| 10 | + - 딕셔너리 자체는 빨리 떠올렸으나 Key 중복이 될 수 있다고 잘못 판단하여 시간을 오래 소모 |
| 11 | + - 실제로 하나의 숫자는 최대 두 번까지 사용되어 구조 상 Key가 중복되지 않음 |
| 12 | +""" |
| 13 | + |
| 14 | + |
| 15 | +class Solution: |
| 16 | + def twoSum(self, nums: list[int], target: int) -> list[int]: |
| 17 | + nums_dict = {} |
| 18 | + |
| 19 | + for idx1, num1 in enumerate(nums): |
| 20 | + num2 = target - num1 |
| 21 | + idx2 = nums_dict.get(num2) |
| 22 | + |
| 23 | + if idx2 is None: |
| 24 | + nums_dict.update({num1: idx1}) |
| 25 | + else: |
| 26 | + return [idx1, idx2] |
| 27 | + |
| 28 | + raise Exception("Invalid nums and target") |
| 29 | + |
| 30 | + |
| 31 | +if __name__ == "__main__": |
| 32 | + test_cases = [ |
| 33 | + ([2, 7, 11, 15], 9, {0, 1}), |
| 34 | + ([3, 2, 4], 6, {1, 2}), |
| 35 | + ([3, 3], 6, {0, 1}), |
| 36 | + ([-2, -3, 0, 3], 1, {0, 3}), |
| 37 | + ([0, -5, 2, 6], -3, {1, 2}), |
| 38 | + ([4, 7, 2, 0, 0], 0, {3, 4}), |
| 39 | + ] |
| 40 | + |
| 41 | + solution = Solution() |
| 42 | + for idx, case_ in enumerate(test_cases): |
| 43 | + nums, target, answer = case_ |
| 44 | + result = solution.twoSum(nums, target) |
| 45 | + assert answer == set( |
| 46 | + result |
| 47 | + ), f"Test Case {idx} Failed: Expected {answer}, Got {result}" |
0 commit comments