--- title: "#1 Two Sum" tags: LeetCode, Top100 --- #1 Two Sum == 題目描述 -- Given an array of integers ==nums== and an integer ==target==, return indices of the two numbers such that they add up to ==target==. You may assume that each input would have ***exactly* one solution**, and you may not use the same element twice. You can return the answer in any order. ### Example 1: >Input: nums = [2,7,11,15], target = 9 >Output: [0,1] >Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 解題思維 -- 利用題目的唯一解,利用hashtable唯一key的特性,邊建表跟查表找出解。 One-pass Hash Table -- ```python from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: h = {} for i, num in enumerate(nums): n = target - num if n in h: return [h[n], i] else: h[num] = i return [] if __name__ == "__main__": nums = [2, 7, 11, 15] a = 9 ans = Solution().twoSum(nums, a) print(ans) ```